pythonxinding 2021-04-22 11:19 采纳率: 100%
浏览 1146
已采纳

Python 爬虫 代码不报错,也不显示爬取内容

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)

以上代码可以用正常运行,且可以爬取相应内容,

希望有老师可以帮忙解答疑惑,谢谢

  • 写回答

4条回答 默认 最新

  • CSDN专家-孙老师 2021-04-22 11:41
    关注

    代码逻辑问题,main函数里只有计算耗时的部分,没有调用get_html、parse_html等函数。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn