需求:爬取某手机app的用户头像与昵称
系统:MacOS
浏览器:Chrome
1.使用Charles找到数据接口-具体使用方式可自行百度
经过测试,发现用户信息主要靠userId
控制
2.编写爬虫代码
from urllib.parse import urlencode
import requests
url = '' # 请求的url地址
headers = { # 带上请求头
"User-Agent": "",
"referer": "",
"set-cookie": "",
}
parm = {
'userId': '20239515'
}
ajax_url = url + urlencode(parm)
response = requests.get(ajax_url, headers=headers)
print(response.status_code)
print(response.text)
然后发现网页数据是通过js加载的,,,陷入沉思
3.分析js代码
找到数据
找到js文件,下载后阅读,看着有点迷茫,解码也没解出来。。。(渣渣咸鱼看不懂)
3.使用selenium进行页面数据提取
一条路走不通,就换条路,直接用selenium提取页面数据,进行数据爬取
chromedriver下载:http://chromedriver.storage.googleapis.com/index.html
Chrome版本查询:chrome://version/
然后下载对应版本 下载到本地后解压,记录当前文件目录
在页面中找到用户id和头像元素所在位置,利用find_element_by_class_name()
将元素提取出来,src需要用get_attribute()
进一步提取
import random
from selenium import webdriver # 导入库
from selenium.webdriver.chrome.options import Options
import urllib.request
def random_id(): # 随机生成userId
userId = random.randint(1000000, 9999999)
return userId
def get_txt(userId):
# 无界面运行
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# chromedriver地址
chrom_driver = 'chromedriver地址/chromedriver'
browser = webdriver.Chrome(executable_path=chrom_driver, chrome_options=chrome_options) # 声明浏览器
# userId = 1023955
url = '请求的url地址?userId={}'.format(userId)
browser.get(url) # 打开浏览器预设网址
try:
nickname = browser.find_element_by_class_name('title').text
image = browser.find_element_by_class_name('image__image').get_attribute('src') + '.jpg'
strs = nickname + ' ' + image
urllib.request.urlretrieve(image, '/Users/apple/Desktop/images/%s.jpg' % nickname)
filename = '/Users/apple/Desktop/images/nickname.txt'
with open(filename, 'a') as file:
file.write(strs + "\n")
print(strs)
except:
print('该用户不存在')
browser.quit()
if __name__ == '__main__':
for i in range(1, 10):
userId = random_id()
get_txt(userId)