多线程爬虫出现报错多线程爬虫出现报错AttributeError: ‘NoneType’ object has
no attribute ‘xpath’
多线程爬虫出现报错多线程爬虫出现报错AttributeError: ‘NoneType’ object has no attribute ‘xpath’一、前言二、问题三、思考和解决问题
四、运行效果
一、前言一、前言
mark一下,本技术小白的第一篇CSDN博客!
最近在捣鼓爬虫,看的是机械工业出版社的《从零开始学Python网络爬虫》。这书吧,一言难尽,优点是案例比较多,说的
也还算清楚,但是槽点更多:1、较多低级笔误;2、基础知识一笔带过,简单得不能再简单,对Python基础不好的人不友
好;3、代码分析部分,相同的代码反复啰嗦解释多次,而一些该解释的新代码却只字不提;4、这是最重要的一点,但也不
全是本书的锅。就是书中用于案例的很多网页经过一段时间(即从书出版时到现在看书),从网站风格和样式都已经发生了很
大变化,导致书中很多代码都不能用了。
二、问题二、问题
这两天看到爬虫的多线程部分,用简书网站的网页练手,并对比串行爬虫和多线程爬虫的效率。串行爬虫运行正常,多线程爬
虫报错:AttributeError: ‘NoneType’ object has no attribute ‘xpath’。代码如下:
import requests
from lxml import etree
import pymongo
import re
from multiprocessing import Pool
import time
client = pymongo.MongoClient('localhost',27017)
mydb = client['mydb'] jianshu_reping = mydb['jianshu_reping']
def get_reping_infoes(url):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86
Safari/537.36'
}
res = requests.get(url,headers=headers)
selector = etree.HTML(res.text)
# print("selector type:", type(selector),"response statue code:",res.status_code)
titles = selector.xpath('//a[@class="title"]/text()')
authors = selector.xpath('//a[@class="nickname"]/text()')
abstracts = selector.xpath('//p[@class="abstract"]/text()')
comments = re.findall('iconfont ic-list-comments".*?(.*?)',res.text,re.S)
rewards = re.findall('iconfont ic-list-like".*?(.*?)',res.text,re.S)
for title,author,abstract,comment,reward in zip(titles,authors,abstracts,comments,rewards):
info = {
"title":title,
"author":author,
"abstract":abstract.strip(),
"comment":comment.strip(),
"reward":reward.strip()
}
jianshu_reping.insert_one(info)
# time.sleep(1)
if __name__ == '__main__':
urls = ['https://www.jianshu.com/c/e048f1a72e3d?order_by=added_at&page={}'.format(i) for i in range(1,10)] start_time1 =
time.time()
for url in urls:
get_reping_infoes(url)
end_time1 = time.time()
print("串行爬虫时间:",end_time1-start_time1)
start_time2 = time.time()
pool = Pool(processes=2)
pool.map(get_reping_infoes,urls)
end_time2 = time.time()
print("2线程爬虫时间:",end_time2-start_time2)
首先想到的是百度,但是翻了几页,都找不到几个跟我类似的情况,就算找到一两个相似的,所提出的方法也不管用。
评论0
最新资源