首页 > 解决方案 > 将数据从 HTML 导出到 Excel

问题描述

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

from bs4 import BeautifulSoup
import urllib
import requests
import re

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

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

打印(汤。美化())

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())

标签: pythonhtmlpython-3.xhtml-lists

解决方案


有很多方法,一种是使用“find_all”并尝试像“a”这样的标签,就像你做的那样。如果这是唯一的选择,那么在输出中使用正则表达式。你可以参考这个线程:Python BeautifulSoup Extract specific URLs。还请向我们展示您要提取的链接的链接或 html 结构。我们希望看到 URL 之间的差异。

PS:对不起,我不能发表评论,因为 <50 声望,否则我会发表评论。

根据理解更新答案:

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)

推荐阅读