【发布时间】:2021-01-20 14:00:54
【问题描述】:
我是 Python 新手,对一般的编程也很陌生。我正在尝试编写一个脚本,该脚本使用 BeautifulSoup 解析 https://www.state.nj.us/mvc/ 的任何红色文本。我看的表格是比较简单的HTML:
<html>
<body>
<div class="alert alert-warning alert-dismissable" role="alert">
<div class="table-responsive">
<table class="table table-sm" align="center" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="24%">
<strong>
<font color="red">Bakers Basin</font>
</strong>
</td>
<td width="24%">
<strong>Oakland</strong>
</td>
...
...
...
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
例如,从上面我想找到贝克斯盆地,而不是奥克兰。
这是我编写的 Python(改编自 Cory Althoff The Self-Taught Programmer,2017,Triangle Connection LCC):
import urllib.request
from bs4 import BeautifulSoup
class Scraper:
def __init__(self, site):
self.site = site
def scrape(self):
r = urllib.request.urlopen(self.site)
html = r.read()
parser = "html.parser"
soup = BeautifulSoup(html, parser)
tabledmv = soup.find_all("font color=\"red\"")
for tag in tabledmv:
print("\n" + tabledmv.get_text())
website = "https://www.state.nj.us/mvc/"
Scraper(website).scrape()
我似乎在这里遗漏了一些东西,因为我似乎无法让它刮过桌子并返回任何有用的东西。最终结果是我想添加时间模块并每 X 分钟运行一次,然后让它在某处记录每个站点变红时的消息。 (这一切都是为了让我的妻子找出新泽西最不拥挤的 DMV!)。
非常感谢任何有关让 BeautifulSoup 工作的帮助或指导。
【问题讨论】:
-
试试这个:
soup.find_all('font[color="red"]')。见:MDN - Attribute selectors -
@Mr.Polywhirl CSS 选择器的语法是
soup.select() -
我发现了我的问题 - 似乎这个页面有一个隐藏 HTML 其余部分的元素。我得想办法解决这个问题。
-
Try Selenium。看起来您正在等待内容动态加载。
标签: python html web-scraping beautifulsoup