python - 使用 Beautifulsoup4 查找 .nextsibling

标签 python python-2.7 web-scraping beautifulsoup

我正在尝试从 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() 函数才能获取下一个(第三)列中的下一个链接?

编辑: 正如我被问到的: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
...

关于python - 使用 Beautifulsoup4 查找 .nextsibling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50153092/

相关文章:

python-2.7 - iterrow 的矢量化替代方案

python - 为什么在 Python 中返回元组比返回多个值更快?

python - BeautifulSoup findAll() 给定了多个类?

python - 使用python将字符附加到txt文件中的每一行

json - Pandoc过滤器tikz.py返回 "not a valid json value"

html - 从 OECD 抓取表格

python - flask : changing location of 'migrations' folder

python - 如何通过 Pandas 中的两列计算唯一记录?

r - 使用循环通过网络抓取创建表格

node.js - 使用 nodejs 和 cheerio 解析脚本标签内容