python爬虫——使用bs4爬取搜狗微信文章
·
缺点:该方法只能爬取有限的数量,因为没有使用代理,当爬取一定数量时会出现验证码
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import queue
from urllib.parse import urlencode
import re
# 构建请求头
ua = UserAgent()
headers = {
'user-agent': ua.Chrome,
'cookie': '自己设置'
}
# 声明一个列表,存储字典
data_list = []
def get_index(q):
url = q.get()
# 请求url
resp = requests.get(url, headers=headers)
# 将爬取回来的数据转成bs4格式
soup = BeautifulSoup(resp.content, 'lxml')
# 分析网页结果,抓取ul标签下面的所以li标签
lis = soup.select('.news-list li')
# 遍历li标签,爬取所需要的数据
for li in lis:
# 微信文章题目,select返回的是一个列表
# 使用stripped_strings进行提取题目(stripped_strings可以去除空白字符)
# stripped_strings返回的是一个迭代器,所以使用list转换成列表
title = li.select('h3')[0]
title = ''.join(list(title.stripped_strings))
# 作者
author = li.select('.s-p a')[0].string
# 文章摘要
text = li.select('.txt-info')[0]
text = ''.join(list(text.stripped_strings))
# 时间戳,抓到的数据是这样的document.write(timeConvert('1526012173'))
datetime = li.select('.s2 script')[0].string
# 使用正则表达式提取时间戳
datetime = re.findall(r'\d+', datetime)[0]
# 文章链接,这里获取的是a标签中的data-share属性而不是a标签的href属性
# 因为href属性打开跳转的不是该文章
href = li.select('h3 a')[0].get('data-share')
# 声明一个字典存储数据
data_dict = {}
data_dict['title'] = title
data_dict['author'] = author
data_dict['text'] = text
data_dict['datetime'] = datetime
data_dict['href'] = href
print(data_dict)
data_list.append(data_dict)
def main():
# 声明队列,将url放入队列
q = queue.Queue()
# 爬取10页
for page in range(1, 10):
# 构造url参数
data = {
'query': 'python爬虫',
'type': '2',
'page': page
}
# 使用urlencode对参数进行url编码后拼接url
url = 'https://weixin.sogou.com/weixin?' + urlencode(data)
q.put(url)
# 如果队列不为空则继续爬取
while not q.empty():
get_index(q)
if __name__ == '__main__':
main()
print(data_list)
更多推荐
所有评论(0)