Skip to main content
 首页 » 编程设计

python之使用 Beautifulsoup4 查找 .nextsibling

2024年09月07日7xiaohuochai

我正在尝试从 URL 获取表格的(某些)内容。 到目前为止,我已经设法获得了页面的两个所需内容,但还有第三个(第三列)我只想获得它的文本。问题是,底层链接存在于页面的其他地方(具有不同的文本),如果我想将表加载到 SQL 数据库中,第三列的内容将与前两列不匹配。

import urllib2 
from bs4 import BeautifulSoup4 
startURL = "http://some.url/website.html" 
page = urllib2.urlopen(startURL).read() 
soup = BeautifulSoup(page, "html.parser") 
for links in soup.findAll("a"): 
    if "href" in links.attrs: 
        www = links.attrs.values() 
        if not "https://" in www[0]:  # to exclude all non-relative links, e.g. external links 
            if "view/" in www[0]: # To get only my desired links of column 1 
                link_of_column1 = www[0]   # this is now my wanted link 

好的,使用这段代码我可以获得第二列。我必须在哪里以及如何应用 .nextsibling() 函数来获取下一(第 3)列中的下一个链接?

编辑: 正如我被问到的:URL 是 https://myip.ms/browse/web_hosting/World_Web_Hosting_Global_Statistics.html我想从第 2 列和第 3 列中获取内容,即“托管公司”(链接文本和链接)和“国家/地区”(仅文本)。

编辑2: 另一件事我忘记了...我如何提取其 137,157 条记录 的信息?

请您参考如下方法:

首先使用其 id=web_hosting_tbl 属性找到包含所有信息的表。然后遍历表的所有行。但是,如果您查看页面源代码,您需要的行不是连续的,而是交替的,并且它们没有任何类名。此外,表格的第一行是标题行,因此我们必须跳过它。

得到需要的行后(使用table.find_all('tr')[1::2]),找到所有的列,然后从相应的列中得到需要的信息。

代码:

import requests 
from bs4 import BeautifulSoup 
 
r = requests.get('https://myip.ms/browse/web_hosting/World_Web_Hosting_Global_Statistics.html') 
soup = BeautifulSoup(r.text, 'lxml') 
 
table = soup.find('table', id='web_hosting_tbl') 
for row in table.find_all('tr')[1::2]: 
    all_columns = row.find_all('td') 
    name = all_columns[1].a.text 
    link = all_columns[1].a['href'] 
    country = all_columns[2].a.text 
    print(name, link, country, sep=' | ') 

部分输出:

Godaddy.com, LLC | /view/web_hosting/2433/Godaddy_com_LLC.html | USA 
Cloudflare, Inc | /view/web_hosting/4638/Cloudflare_Inc.html | USA 
Amazon.com, Inc | /view/web_hosting/615/Amazon_com_Inc.html | USA 
Ovh Sas | /view/web_hosting/7593/Ovh_Sas.html | France 
Hetzner Online Ag | /view/web_hosting/45081/Hetzner_Online_Ag.html | Germany 
Hostgator.com Llc | /view/web_hosting/26757/Hostgator_com_Llc.html | USA 
Google Inc | /view/web_hosting/617/Google_Inc.html | USA 
Bluehost Inc | /view/web_hosting/3886/Bluehost_Inc.html | USA 
...