import requests
from lxml import etreeimport time
class MovieSpider(object):
def __init__(self):
self.headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
self.url='https://m.qidian.com/rank/yuepiao/male'
def get_html(self,url):
resp=requests.get(url,headers=self.headers)
html=resp.text
self.parse_html(html)
def parse_html(html):
xp_html=etree.HTML(html)
titles=xp_html.xpath('//*[@id="books"]/li/a/div/div[1]/h4/text()')
labels=xp_html.xpath('//*[@id="books"]/li/a/div/p[1]/em[1]/text()')
authors=xp_html.xpath('//*[@id="books"]/li/a/div/div[2]/div/span/text()')
print(titles,labels,authors)
#for title,label,author in zip(titles,labels,authors):
#print(title,label,author)
def main(self):
start_time =time.time()
# for i in range(0,100,25):
# url=self.url.format(i)
# self.get_html(url)
end_time=time.time()
print('共耗时:',end_time-start_time)
spider=MovieSpider()
spider.main()
代码运行正常,但结果只有耗时显示,直接运行爬虫代码可以显示正常的爬取内容,写成上述函数无法显示爬取内容,什么问题造成的?
import requests
import time
url='https://m.qidian.com/rank/yuepiao/male'
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
resp=requests.get(url,headers=headers)
from lxml import etree
html=resp.text
parse_html=etree.HTML(html)
start_time=time.time()
titles=parse_html.xpath('//*[@id="books"]/li/a/div/div[1]/h4/text()')
labels=parse_html.xpath('//*[@id="books"]/li/a/div/p[1]/em[1]/text()')
authors=parse_html.xpath('//*[@id="books"]/li/a/div/div[2]/div/span/text()')
s=len(authors)
i=0
while i<s:
if authors.count('\n '):
authors.remove('\n ')
else:
break
for title,label,author in zip(titles,labels,authors):
print(title,label,author)
end_time=time.time()
print('共耗时:',end_time-start_time)
以上代码可以用正常运行,且可以爬取相应内容,
希望有老师可以帮忙解答疑惑,谢谢
代码逻辑问题,main函数里只有计算耗时的部分,没有调用get_html、parse_html等函数。
写打印语句测试一下,看看问题出现在哪一行,参数的传值是否正常。
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y