【发布时间】:2019-06-18 05:31:55
【问题描述】:
我正在使用 Python(3.7) 和 BeautifulSoup(4) 开发一个项目,在该项目中我需要在不知道 HTML 的确切结构的情况下抓取一些数据,但通过假设用户相关信息将在headings, paragraph, pre and code 标签中。在这些标签的find_all 之后,我想将headings and paragraph 标签与code and pre 标签与ResultSet 对象分开。
这是我尝试过的:
required_tags = ["h1", "h2", "h3", "h4", "h5", "pre", "code", "p"]
text_outputs = []
code_outputs = []
pages = [
"https://bugs.launchpad.net/bugs/1803780",
"https://bugs.launchpad.net/bugs/1780224",
"https://docs.openstack.org/keystone/pike/_modules/keystone/assignment/core.html",
"https://openstack-news.blogspot.com/2018/11/bug-1803780-confusing-circular.html",
"https://www.suse.com/documentation/suse-openstack-cloud-9/doc-cloud-upstream-user/user"
"/html/keystone/_modules/keystone/assignment/core.html"
]
page = requests.get(pages[0])
html_text = BeautifulSoup(page.text, 'html.parser')
text = html_text.find_all(required_tags)
elements = []
for e in html_text:
elements.append(e.parent)
for t in text:
for e in elements:
if e == 'code' or e == 'pre':
print(e)
code_outputs.append(t.get_text())
else:
text_outputs.append(t.get_text())
但它不会返回 code_outputs 和 text_outputs 中的任何内容。
提前致谢!
【问题讨论】:
-
您要解析什么网址?请补充
-
这是一个 url 列表,让我补充一下!
-
是的,添加所有相关代码以减少猜测
-
嗨@DeveshKumarSingh 我已经添加了所有
urls。 -
你能仔细检查你拥有的网址是否真的有代码和前置标签吗?我不认为他们都有
标签: python python-3.x web-scraping beautifulsoup