【发布时间】:2021-11-14 08:33:30
【问题描述】:
我正在编写一个 python 脚本来抓取网页并将信息存储到列表中。 网页结构不好,所以内置过滤功能对我不起作用。 因此,我正在尝试为 find_all() 开发一个自定义过滤函数。
我要过滤的是这样的:
<td id="td343_23" style=display:>text</td>
地点:
"td34_23" 因每个而异,因此需要正则表达式。 标签“td”应被过滤,但应排除具有相似属性的标签“th”。 “style=display:”或“style”(无值)应被过滤,但“style=display:none”应被排除。
我所做的是:
重新导入 从 bs4 导入 BeautifulSoup4
def visibility(tag):
displaynone = re.compile('(?!display:none)')
idvalue = re.compile('td[0-9]+_[0-9]+')
return bool(displaynone.search(tag.get('style'))) and tag.select('td') and bool(idvalue.search(tag.get('id')))
parsed = BeautifulSoup(html, 'html.parser')
filtered = parsed.find_all(visibility)
上面的代码根本不起作用。 请告诉我如何编写过滤条件。
任何帮助将不胜感激。 谢谢。
于 2021 年 9 月 21 日编辑
该页面属于私密页面,因此我无法提供网址。 但是,下面是 HTML 示例。
<html>
<div class="block">
<thread>
<tr>
<th id="td18_8" style>include</th>
<th id="td18_9" style="display:">include</th>
<th id="td18_10" style="display:none">exclude</th></tr>
</thread>
<thread>
<tr>
<th id="td19_8" style>include</th>
<th id="td19_9" style="display:">include</th>
<th id="td19_10" style="display:none">exclude</th>
</tr>
</thread>
</div>
</boxy>
<html>
【问题讨论】:
-
您能否提供一个包含该信息和预期结果的 url 会很好。
-
@HedgeHog 感谢您的评论!我添加了与原始网页结构相似的示例 HTML 数据。
标签: python html css web-scraping beautifulsoup