python - 将数据从 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())
解决方案
有很多方法,一种是使用“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)
推荐阅读
- pandas - 使用公共轴绘制两个变量的分箱相关性
- java - 为什么一个空的 else-if 语句是不好的风格,我应该如何重写它?
- javascript - 从嵌套的 javascript 对象中获得普通的一天?
- node.js - Babel 7 - 节点静态类方法未定义
- python - 从元组中获取前 n 个结果
- r - 如何为 geom_line 创建的图表中的选定行添加标签?
- angular - 带有角度折叠列表视图的 Nativescript
- c# - 如何在 FluentValidation 中设置选项?
- excel - VBA - 当所有列都为 0 时删除行
- excel - 在循环VBA中选择多个不同的范围