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)
以上代码可以用正常运行,且可以爬取相应内容,
希望有老师可以帮忙解答疑惑,谢谢