【问题标题】:Flask web scraper problem with table head dataFlask web 刮板问题与表头数据
【发布时间】:2020-11-12 05:07:11
【问题描述】:

我正在尝试制作一个获取游戏标题信息的网络爬虫。目前我正在从维基百科上的 ps4 游戏列表中抓取。我这样做是因为我正在尝试学习如何将诸如网络爬虫之类的脚本合并到烧瓶项目中。

我让它工作得很好,但我无法获得<thead> 数据。列名在此处列出,我希望将这些添加到我生成的 csv 文件中。我想通过尝试定位 <hr> 标签我可以获得我需要的东西,但它不能很好地工作。这是我最近的尝试:

import requests
from bs4 import BeautifulSoup
import csv

class GameScraper:
    results = []

    def fetch(self, url):
        return requests.get(url)

    def parse(self, html):
        content = BeautifulSoup(html, 'lxml')
        table = content.find(id="softwarelist")
        rows = table.findAll('tr')
        header = table.find('thead')
        header_row = header.findAll('tr')
        results = header_row.findAll('th')       
        

        for row in rows:           
            if len(row.findAll('td')):
                self.results.append([data.text for data in row.findAll('td')])

    def to_csv(self):
        with open('ps4.csv', 'w') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerows(self.results)

    def run(self):        
        ps4_list = self.fetch('https://en.wikipedia.org/wiki/List_of_PlayStation_4_games')
        self.parse(ps4_list.text)
        self.to_csv()

if __name__ == '__main__':
    scraper = GameScraper()
    scraper.run()

我目前收到此错误:

AttributeError: 'NoneType' object has no attribute 'findAll'

在这一行:

header_row = header.findAll('tr')

【问题讨论】:

  • 您是否要获取所有内容?你的桌子上没有任何东西叫thead。
  • 你想要的信息在tbody标签而不是thead
  • 它在 我想要包含 Title、Genre、Developer、Platform、Release Date 的 。目前我的脚本获得了我想要的实际游戏信息,只是没有获得标题信息。我希望 csb 具有我刚刚在第 1 行中列出的术语,以便您知道游戏数据是什么

标签: python beautifulsoup


【解决方案1】:

看起来当您向维基百科发送请求时返回的页面与向普通用户显示的页面不同。在你的程序接收到的页面中,在用户端head中的Title、Genre、Developer、Platform、Release Date等数据实际上只是存储在<tbody>中的<th>中。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2014-07-11
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多