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

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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改