我正在使用Python(3.7)和BeautifulSoup(4)实施一个项目,以实施抓取解决方案。
注意:我已经搜索找到解决问题的方法,但是找不到任何解决方法,因为它与通常我们需要的抓取方法不同。所以,这就是为什么,请不要将此标记为重复!
该项目分为两个部分:
那么,我们如何在不知道实际标签/类的情况下从网页中获取搜索词的相关信息?
这是我到目前为止所做的:
soup = BeautifulSoup(driver.page_source, 'lxml')
result_div = soup.find_all('div', attrs={'class': 'g'})
links = []
titles = []
descriptions = []
for r in result_div:
# Checks if each element is present, else, raise exception
try:
link = r.find('a', href=True)
title = None
title = r.find('h3')
if isinstance(title, Tag):
title = title.get_text()
description = None
description = r.find('span', attrs={'class': 'st'})
if isinstance(description, Tag):
description = description.get_text()
# Check to make sure everything is present before appending
if link != '' and title != '' and description != '':
links.append(link['href'])
titles.append(title)
descriptions.append(description)
# Next loop if one element is not present
except Exception as e:
print(e)
continue
答案 0 :(得分:1)
在HTML字符串中很容易找到包含关键字或正则表达式的元素,这就是您可以做到的。
这将返回HTML页面中包含您要查找的关键字的每个元素。
from bs4 import BeautifulSoup
import re
html_text = """
<h2>some other text</h2>
<p>text you want to find with keyword</p>
<h1>foo bar foo bar</h1>
<h2>text you want to find with keyword</h2>
<a href="someurl">No idea what is going on</a>
<div> text you want to find with keyword</div>
"""
soup = BeautifulSoup(html_text)
for elem in soup(text=re.compile(r'\bkeyword\b | \bkey_word\b | \something else\b | \bone_more_maybe\b')):
print(elem.parent)