【问题标题】:Scraping Data using BS4 gives me unexpected results使用 BS4 抓取数据给了我意想不到的结果
【发布时间】:2019-09-26 14:13:41
【问题描述】:

我不想用我的基本问题惹恼你,但我被困住了,希望你能帮助我。 我已经完成了教程并观看了许多视频,但我无法弄清楚我做错了什么。 我想从这个表中抓取数据:https://www.youpriboo.com/vorher_102_main_nat.php?action=show&liga=2.BL

这是我的代码:

import requests
from bs4 import BeautifulSoup

base_URL = 'https://www.youpriboo.com/vorher_102_main_nat.php?action=show&liga='
liga = '2.BL'
URL = base_URL + liga

headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36:'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

for name in soup.find_all("td", class_="hac"):
    name1 = name.parent.find_all('td')[1] # team1 
    name2 = name.parent.find_all('td')[2] # team2
    wahr1 = name.parent.find_all('td')[6] # wahr1
    print(name1.get_text() +' '+ name2.get_text()+' '+ wahr1.get_text())

问题是它给了我 3 次数据,并且在游戏之间列出了 3 个数字。

预期结果如下所示:

Armina Bielefeld VfB Stuttgart 34,43
SV Wehen Wiesbaden VfL Osnabrück 34,51
(and so on)

感谢您的时间和工作!

我也在这里发布了这个:https://www.reddit.com/r/Python/comments/d9km7y/scraping_data_using_bs4_gives_me_unexpected/

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    您可以通过几种不同的方式将结果抓取并写入 csv 文件。我更喜欢和熊猫一起去。首先尝试使用 :has() 来过滤掉不需要的内容。那就是说以下应该起作用:

    import requests
    import pandas as pd
    from bs4 import BeautifulSoup
    
    base_URL = 'https://www.youpriboo.com/vorher_102_main_nat.php?action=show&liga='
    liga = '2.BL'
    
    URL = f"{base_URL}{liga}"
    
    page = requests.get(URL, headers={"User-Agent": 'Mozilla/5.0'})
    soup = BeautifulSoup(page.content, 'html.parser')
    
    df = pd.DataFrame(columns=['Name_One','Name_Ano','Wahr'])
    for tr in soup.select('.prognose_tab_1 tr:has(.greycell)'):
        name1 = tr.select('.hac')[1].get_text()
        name2 = tr.select('.hac')[2].get_text()
        wahr1 = tr.select('.greycell')[0].get_text()
        df = df.append({'Name_One':name1, 'Name_Ano':name2, 'Wahr':wahr1}, ignore_index=True)
    
        print(f"{name1} {name2} {wahr1}")
    
    df.to_csv("youpriboo.csv", encoding='utf-8', index=False)
    

    【讨论】:

    • 哇!太棒了!非常感谢!现在我必须弄清楚它为什么起作用:D
    • 嗨,Sim,我还在弄清楚发生了什么。我尝试选择数字 Über 和 Unter,但问题是它们没有像 .hac 或 .greycell 这样的类,它们只是 53,94。我试过 unter = tr.select('.td') 但它告诉我“超出范围”。我想在其他信息之后立即获得此信息。你能告诉我如何抓住它吗? Team1 Team2 1 0 X unter über
    • 您可以使用unter = tr.select('td')[-4].get_text()uber = tr.select('td')[-3].get_text() 获取它们。顺便说一句,如果您想获得更多领域或带来任何改变,请务必提出一个新问题。谢谢。
    • 哦,伙计,正是那个点搞砸了我的选择器。我要学习很多...非常感谢,再次!
    【解决方案2】:

    过滤不正确。试试这个方法,

    table = soup.find_all("tr")
    #print(table)
    for row in table:
        data = row.find_all("td", class_="hac")
        if(len(data)>0):
            print(data[1].get_text(),data[2].get_text())
    
        data = row.find_all("td", class_="greycell")
        if(len(data)>0):
            print(data[0].get_text())
    

    【讨论】:

    • 不错!谢谢你。但是我可以像我的例子那样在团队之后从 graycell 打印数据吗?
    • 如果你想要所有来自 graycell 的数据,只需打印数据。该索引用于识别单元格。
    【解决方案3】:

    试试下面的代码。这会给你预期的输出。

    import requests
    from bs4 import BeautifulSoup
    
    base_URL = 'https://www.youpriboo.com/vorher_102_main_nat.php?action=show&liga='
    liga = '2.BL'
    URL = base_URL + liga
    
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36:'}
    
    page = requests.get(URL, headers=headers)
    
    soup = BeautifulSoup(page.content, 'html.parser')
    table=soup.select_one(".prognose_tab_1")
    for tr in table.select('tr'):
      if tr.select('.hac') and tr.select('.greycell'):
         name1=tr.select('.hac')[1]
         name2 = tr.select('.hac')[2]
         wahr1 = tr.select('.greycell')[0]
    
         print(name1.get_text() +' '+ name2.get_text()+' '+ wahr1.get_text())
    

    输出

    Arminia Bielefeld VfB Stuttgart 34,43
    SV Wehen Wiesbaden VfL Osnabrück 34,51
    Jahn Regensburg Hamburger SV 24,18
    Karlsruher SC 1. FC Heidenheim 37,70
    VfL Bochum SV Darmstadt 98 55,22
    Erzgebirge Aue Dynamo Dresden 37,70
    FC St. Pauli SV Sandhausen 43,90
    SpVgg Greuther Fürth Holstein Kiel 46,23
    Hannover 96 1. FC Nürnberg 46,23
    

    【讨论】:

    • 谢谢,但有问题 ``` soup = BeautifulSoup(page.content, 'html.parser') ``` 它说“意外缩进”
    • @Siggi:你现在可以试试吗?
    • 不错!非常感谢你!有没有一种简单的方法可以将输出放入 excel 或 .CSV?
    • 是的,你可以。如果你使用 pandas 数据框,它更容易将数据放入 CSV
    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 2017-01-05
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2021-12-17
    • 2021-04-22
    相关资源
    最近更新 更多