(一) 知乎热榜
网址:https://www.zhihu.com/hot
目标:获取知乎热榜内容,并保存至本地。
网站类型:静态(数据直接嵌入在HTML中)
实现步骤:
- 登录知乎,获取cookie值;
- 打开浏览器的开发者工具(F12)查看网页结构;
- 根据网页结构写数据提取的语法,这里我用的
Xpath
;
import requests
from lxml import etree
url = 'https://www.zhihu.com/hot'
headers = {
# 伪装正常用户
'user-agent': 'Pass',
'cookie': '因为知乎现在不登录是无法正常访问到的,因为这里还没学到其他方法只能先用cookie这个笨方法了'
}
# 发送请求并获取响应
try:
response = requests.get(url=url, headers=headers, timeout=5)
response.raise_for_status() # 检查是否成功
except requests.exceptions.RequestException as e:
print(f'请求失败: {
e}')
exit()
# 解析HTML
html_code = etree.HTML(response.text)
title = html_code.xpath('//*[@id="TopstoryContent"]//section//h2/text()')
# 遍历数据并保存
for line in title:
with open('./Data/Hot.txt', 'a', encoding='utf-8') as f:
f.write(line + '\n')
print('今日热榜, 保存完成...')
(二) 虎牙星秀
网址:https://www.huya.com/g/1663
目标:获取娱乐天地[星秀]中所以直播间封面
网站类型:动态(数据通过JavaScript进行加载)
实现步骤:
- 打开浏览器开发者工具(f12);
- 切换到网络选项,进行翻页获取数据地址。
import requests
# iPageNo(页数), iPageSize(一页最大显示)
url = 'https://live.huya.com/liveHttpUI/getLiveList?iGid=1663&iPageNo=1&iPageSize=120'
headers = {
# 伪装正常用户
'user-agent': '',
}
# 请求并返回响应
try:
response = requests.get(url, headers=headers, timeout=5)
response.raise_for_status() # 检查是否成功请求
except requests.exceptions.RequestException as e:
print('请求失败', e)
# 解析数据
live_data = response.json()['vList']
for live in live_data:
# 主播名字
anchor = live['sNick']
# 直播间封面
cover = live['sScreenshot']
response = requests.get(url=cover, headers=headers, timeout=5).content
# 保存直播间封面, 并以主播名作为图片的名称。
with open('./Data/hy/' + anchor + '.jpg', 'wb') as f:
f.write(response)
print(anchor, '保存成功...')
(三) 微信公众号
网址:https://mp.weixin.qq.com/s/fwZgMNdaCxRrxgxzbR2mBw
目标:获取微信公众号任意文章中的所以图片,并保存到本地。
网站类型:静态(数据直接嵌入在HTML中)
实现步骤:
- 查看网页结构;
- 分析存放链接的img标签;
- 定位标签,提取其中的data-src属性;
import requests
from bs4 import BeautifulSoup
url = 'https://mp.weixin.qq.com/s/fwZgMNdaCxRrxgxzbR2mBw'
headers = {
# 伪装正常用户
'user-age