gpt4 book ai didi

python - 在 BeautifulSoup 期间拉取 HTML 标记之间的特定(文本)间隔

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:17 25 4
gpt4 key购买 nike

当我在“检查元素”模式下查看归类为(文本)的内容时,我试图提取它:

<div class="sammy"
<div class = "sammyListing">
<a href="/Chicago_Magazine/blahblahblah">
<b>BLT</b>
<br>
"
Old Oak Tap" <---**THIS IS THE TEXT I WANT**
<br>
<em>Read more</em>
</a>
</div>
</div>

这是迄今为止我的代码,有问题的行是最后的底部列表理解:

STEM_URL = 'http://www.chicagomag.com'
BASE_URL = 'http://www.chicagomag.com/Chicago-Magazine/November-2012/Best-Sandwiches-Chicago/'

soup = BeautifulSoup(urlopen(BASE_URL).read())
sammies = soup.find_all("div", "sammy")
sammy_urls = []
for div in sammies:
if div.a["href"].startswith("http"):
sammy_urls.append(div.a["href"])
else:
sammy_urls.append(STEM_URL + div.a["href"])
restaurant_names = [x for x in div.a.content]

我尝试过 div.a.br.contentdiv.br,但似乎无法正确执行。

如果建议采用正则表达式方式,如果可能的话,我也非常感谢非正则表达式方式。

最佳答案

使用 CSS selector 找到每个列表的 b 元素和 find the next text sibling :

for b in soup.select("div.sammy > div.sammyListing > a > b"):
print b.find_next_sibling(text=True).strip()

演示:

In [1]: from urllib2 import urlopen

In [2]: from bs4 import BeautifulSoup

In [3]: soup = BeautifulSoup(urlopen('http://www.chicagomag.com/Chicago-Magazine/November-2012/Best-Sandwiches-Chicago/'))

In [4]: for b in soup.select("div.sammy > div.sammyListing > a > b"):
...: print b.find_next_sibling(text=True).strip()
...:
Old Oak Tap
Au Cheval
...
The Goddess and Grocer
Zenwich
Toni Patisserie
Phoebe’s Bakery

关于python - 在 BeautifulSoup 期间拉取 HTML 标记之间的特定(文本)间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30335704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com