weixin_71580395 2022-06-07 18:53 采纳率: 50%
浏览 72
已结题

Python爬虫数据,需要抓图和代码

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果 第一题需要代码,第二题代码抓图都需要。

img

img

img

  • 写回答

2条回答 默认 最新

  • 溪风沐雪 2022-06-07 19:44
    关注
    from bs4 import BeautifulSoup
    import pandas as pd
    import requests
    from urllib.request import urlopen
    
    def getContent(url):
        myURL = urlopen(url)
        if myURL.getcode()==200:
            content = myURL.read()
        elif myURL.getcode()==418:     
            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
            req = requests.get(url, headers=headers)
            content = req.text
        else:
            content = None
            print("爬取失败!")
            return None
        bsObj = BeautifulSoup(content, 'lxml')
        return bsObj
    
    def getList(url):
        names = []
        authors = []
        prices = []
        bsobj = getContent(url)
        if bsobj:
            bs = bsobj.find_all('div', {'class': 'imgmain2_r floatleft_q'})
            for i in range(0, len(bs)):
                book_name = bs[i].find('p',{"style":"height:40px"}).find('a').text
                author = bs[i].find('p',{"style":"height:20px"}).text.split('\n')[1]
                price =  bs[i].find('p',{"class":"dj_r"}).text.split(':')[1]
                names.append(book_name)
                authors.append(author)
                prices.append(price)
        return names,authors,prices
    url = 'http://www.cyp.com.cn/?action-model-name-specialbooksort-itemid-3.html'
    names,authors,prices = getList(url)
    bookInfos = pd.DataFrame({'书名': names, '作者': authors, '定价':prices})
    bookInfos.to_csv('pachong_XYY.csv', encoding='gbk')
    

    img

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

报告相同问题?

问题事件

  • 系统已结题 6月16日
  • 已采纳回答 6月8日
  • 创建了问题 6月7日

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?