【问题标题】:How to only scrape the first item in a row using Beautiful Soup如何使用 Beautiful Soup 仅刮取连续的第一项
【发布时间】:2018-12-05 06:28:06
【问题描述】:

我目前正在运行以下 python 脚本:

import requests
from bs4 import BeautifulSoup

origin= ["USD","GBP","EUR"]
i=0
while i < len(origin):
page = requests.get("https://www.x-rates.com/table/?from="+origin[i]+"&amount=1")
soup = BeautifulSoup(page.content, "html.parser")

tables = soup.findChildren('table')
my_table = tables[0]

rows = my_table.findChildren(['td'])

i = i +1


for rows in rows:
    cells = rows.findChildren('a')
    for cell in cells:
        value = cell.string
        print(value)

从这个 HTML 中抓取数据:

https://i.stack.imgur.com/DkX83.png

我遇到的问题是我正在努力只刮第一列而不刮第二列,因为它们都在标签下并且彼此位于同一表格行中。 href 是唯一可以区分两个标签的东西,我尝试使用它进行过滤,但它似乎不起作用并返回一个空白值。此外,当我尝试手动对数据进行排序时,输出被垂直而不是水平修改,我是编码新手,所以任何帮助将不胜感激:)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    当您打印从顶部获得的每个项目时,会更容易跟踪发生的情况,例如在这种情况下,来自表格项目。我们的想法是一件一件地去,这样你就可以跟随了。

    import requests
    from bs4 import BeautifulSoup
    
    origin= ["USD","GBP","EUR"]
    i=0
    while i < len(origin):
        page = requests.get("https://www.x-rates.com/table/?from="+origin[i]+"&amount=1")
        soup = BeautifulSoup(page.content, "html.parser")
        tables = soup.findChildren('table')
        my_table = tables[0]
    
        i = i +1
    
        rows = my_table.findChildren('tr')
        for row in rows:
            cells = row.findAll('td',class_='rtRates')
            if len(cells) > 0:
                first_item = cells[0].find('a')
                value = first_item.string
                print(value)
    

    【讨论】:

      【解决方案2】:

      您可能还想尝试另一种方法来达到同样的效果:

      import requests
      from bs4 import BeautifulSoup
      
      keywords = ["USD","GBP","EUR"]
      
      for keyword in keywords:
          page = requests.get("https://www.x-rates.com/table/?from={}&amount=1".format(keyword))
          soup = BeautifulSoup(page.content, "html.parser")
          for items in soup.select_one(".ratesTable tbody").find_all("tr"):
              data = [item.text for item in items.find_all("td")[1:2]]
              print(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-08
        • 2023-03-13
        • 2018-04-22
        • 2021-08-04
        • 1970-01-01
        • 2019-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多