我正在尝试抓取一个网站,该网站的段落内容由h3标题设置。H3头文件有标题内容(例如,make,model,year),然后段落中的以下文本就是我想要的。理想情况下,我喜欢使用类来识别段落内容,但它们都是同一个类。
此外,我应该说,我是新手,所以请原谅愚蠢的问题或表达不清的问题。
我已经到了可以拉出文本的地步,整个文本都是由html段落标记分隔的。我的想法是,(1)如果我能以某种方式将段落标签之间的内容转换为列表中的单个项目,我可以针对该列表编写一个循环,以将这些项目修改到我正在构建的数据库中。
或者,(2)我想知道是否有某种方法可以从包含特定文本的标题后面的段落中提取兄弟段落文本(例如,福特'Models')。我知道你可以用定义的id和类来做,但是你能根据它包含的文本来识别一个特定的h3标记吗?
在过去的几天里,我一直在看youtube和阅读论坛。任何反馈,如您所愿,直截了当地提供,将不胜感激!我正在使用漂亮的汤,但我很乐意做任何对工作最好的事情。
谢谢!
约翰
这是html -
<div class="entry-content bb">
<h4>Pedigree</h4>
<p>This is where the content is for pedigree that I am trying to scrape</p>
<h4>Breed</h4>
<p>This is where the content is for breed that I am trying to scrape</p>
<h4>Origin</h4>
<p>This is where the content is for origin that I am trying to scrape</p>如果我可以单独识别这个类,下面是我将使用的代码-
pedigree_temp = soup.find(class_='pedigree').text
pedigree_final.append(pedigree_temp)发布于 2021-03-26 09:32:52
对于bs4 4.7.1+,您可以使用:contains将h4标记的内容作为目标,然后使用相邻的同级组合符(+)移动到相邻的p。您可以使用以下语法从要搜索的标头项目列表中生成相应的选择器:
from bs4 import BeautifulSoup as bs
html = '''<div class="entry-content bb">
<h4>Pedigree</h4>
<p>This is where the content is for pedigree that I am trying to scrape</p>
<h4>Breed</h4>
<p>This is where the content is for breed that I am trying to scrape</p>
<h4>Origin</h4>
<p>This is where the content is for origin that I am trying to scrape</p>'''
soup = bs(html, 'lxml')
headers = ['Pedigree', 'Breed']
selector = ', '.join([f'h4:contains("{header}") + p' for header in headers])
print([i.text for i in soup.select(selector)])发布于 2021-03-25 12:36:36
如果你想要你的soup中所有段落标签中的文本列表,可以试试:
[tag.text for tag in soup.select('p')]或者获取包含特定文本的标记列表:
import re
for elem in soup(text=re.compile('find me!')):
print elem.parenthttps://stackoverflow.com/questions/66791248
复制相似问题