【问题标题】:Web scraping with BeautifulSoup使用 BeautifulSoup 进行网页抓取
【发布时间】:2015-11-20 06:08:55
【问题描述】:

我想从这个链接中抓取国家名称和国家首都: https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order

从 html 代码中,我正在寻找所有这些:

from bs4 import BeautifulSoup
import requests

BASE_URL = "https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order"

html = requests.get(BASE_URL).text
soup = BeautifulSoup(html, "html.parser")
countries = soup.find_all("td")

print (countries)

但我不知道如何真正获取标签之间的内容,尤其是因为其中没有任何信息。

我觉得这很简单,但我无法真正理解所有教程,因为它们使用类,而这个 wiki 页面在表格中没有用于其信息的类。

【问题讨论】:

  • 您可以使用任何有效的识别特征来选择要提取的内容。也许您应该通过对您尝试操作的页面的简要分析来更新您的问题。一些常见但脆弱的方法是“在页面上查找第三个表格”或“在第一个小节标题之后查找表格”,但也许您可以想出更强大的方法。

标签: python web-scraping beautifulsoup scrape


【解决方案1】:

您只需要添加一些代码来遍历表列,如下所示:

from bs4 import BeautifulSoup
import requests

BASE_URL = "https://en.wikipedia.org/wiki/List_of_national_capitals_in_alphabetical_order"

capitals_countries = []

html = requests.get(BASE_URL).text
soup = BeautifulSoup(html, "html.parser")
country_table = soup.find('table', {"class" : "wikitable sortable"})

for row in country_table.find_all('tr'):
    cols = row.find_all('td')

    if len(cols) == 3:
        capitals_countries.append((cols[0].text.strip(), cols[1].text.strip()))

for capital, country in capitals_countries:
    print('{:35} {}'.format(capital, country))

这将显示首都和国家/地区对,如下所示:

Abu Dhabi                           United Arab Emirates
Abuja                               Nigeria
Accra                               Ghana
Adamstown                           Pitcairn Islands
Addis Ababa                         Ethiopia
Algiers                             Algeria
Alofi                               Niue
Amman                               Jordan

【讨论】:

    【解决方案2】:

    这个怎么样:

    >>> table = soup.find('table', attrs={'class': 'wikitable'})  # find the table
    >>> tds = table.find_all('td')   # get all the table data
    >>> countries = [tds[i:i+3] for i in range(0, len(tds), 3)]  # get all the countries' data
    >>> result = [[item.text for item in country] for country in countries]  # get the final result
    >>> print ' /'.join(result[0])
    Abu Dhabi / United Arab Emirates /
    

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2020-10-04
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2020-09-13
      相关资源
      最近更新 更多