【问题标题】:Exporting data from HTML to Excel将数据从 HTML 导出到 Excel
【发布时间】:2020-02-18 05:51:10
【问题描述】:

我刚开始编程。 我的任务是将数据从 HTML 页面提取到 Excel。 使用 Python 3.7。 我的问题是,我有一个网站,里面有更多的网址。 在这些网址后面又多了更多的网址。 我需要第三个 url 后面的数据。 我的第一个问题是,我如何指示程序仅从 ul 中选择特定链接,而不是页面上的每个 ul?

from bs4 import BeautifulSoup
import urllib
import requests
import re

page = urllib.request.urlopen("file").read()

soup = BeautifulSoup(page, "html.parser")

打印(soup.prettify())

for link in soup.find_all("a", href=re.compile("katalog_")):
links= link.get("href")
if "katalog" in links:
    for link in soup.find_all("a", href=re.compile("alle_")):
        links = link.get("href")       

打印(soup.get_text())

【问题讨论】:

标签: python html python-3.x html-lists


【解决方案1】:

有很多方法,一种是使用“find_all”并尝试像您一样在“a”之类的标签上具体化。如果这是唯一的选择,那么在输出中使用正则表达式。你可以参考这个帖子:Python BeautifulSoup Extract specific URLs。还请向我们展示您要提取的链接的链接或 html 结构。我们想看看 URL 之间的区别。

PS:对不起,我不能制作 cmets,因为

根据理解更新答案:

from bs4 import BeautifulSoup
import urllib
import requests

page = urllib.request.urlopen("https://www.bsi.bund.de/DE/Themen/ITGrundschutz/ITGrundschutzKompendium/itgrundschutzKompendium_node.html").read()
soup = BeautifulSoup(page, "html.parser")

for firstlink in soup.find_all("a",{"class":"RichTextIntLink NavNode"}):
    firstlinks = firstlink.get("href")
    if "bausteine" in firstlinks:
        bausteinelinks = "https://www.bsi.bund.de/" + str(firstlinks.split(';')[0])
        response = urllib.request.urlopen(bausteinelinks).read()
        soup = BeautifulSoup(response, 'html.parser')
        secondlink = "https://www.bsi.bund.de/" + str(((soup.find("a",{"class":"RichTextIntLink Basepage"})["href"]).split(';'))[0])
        res = urllib.request.urlopen(secondlink).read()
        soup = BeautifulSoup(res, 'html.parser')
        listoftext = soup.find_all("div",{"id":"content"})
        for text in listoftext:
            print (text.text)

【讨论】:

  • 从那个网站开始,我想打开“Bausteine”中的网址并打开后面的网址,然后在最后一页上导出数据
  • 添加 re.compile 我可以将 url 编译为我需要的前 10 个 url。这有帮助。
  • 我仍然不确定您在寻找哪些链接,我已经更新了我的猜测答案,请查看。
  • 我编辑了我的帖子并提取了我正在寻找的网址。现在我需要一种方法来打开找到的网址。如果我理解正确,您的解决方案只会打印它们
猜你喜欢
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2013-10-25
  • 2020-01-27
  • 2018-06-27
  • 2013-02-26
相关资源
最近更新 更多