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

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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵