python - 使用 Beautiful Soup 进行网页抓取,无类抓取多个元素
问题描述
所以我想把导演从这件事上刮下来。但正如我看到的页面,我知道这部电影有两位导演 Danny Boyle 和 Loveleen Tandan。但是如果我使用 find_all('a') 则无法获得它,那么它也会采用 Dev Patel、Freida Pinto 等演员的名字。
我不能使用 find_all('a')[1] 和 find_all('a')[2] 因为其他电影可能只有一个导演。唯一将演员与导演区分开来的是带有类幽灵的跨度标签。假设可能有一个、两个或三个董事,我应该如何收集这些数据。
<p class="">
Directors:
<a href="/name/nm0000965/">
Danny Boyle
</a>
,
<a href="/name/nm0849164/">
Loveleen Tandan
</a>
<span class="ghost">
|
</span>
Stars:
<a href="/name/nm2353862/">
Dev Patel
</a>
,
<a href="/name/nm2951768/">
Freida Pinto
</a>
,
<a href="/name/nm0795661/">
Saurabh Shukla
</a>
,
<a href="/name/nm0438463/">
Anil Kapoor
</a>
</p>
解决方案
这应该可以帮助你:
from bs4 import BeautifulSoup
html = """
<p class="">
Directors:
<a href="/name/nm0000965/">
Danny Boyle
</a>
,
<a href="/name/nm0849164/">
Loveleen Tandan
</a>
<span class="ghost">
|
</span>
Stars:
<a href="/name/nm2353862/">
Dev Patel
</a>
,
<a href="/name/nm2951768/">
Freida Pinto
</a>
,
<a href="/name/nm0795661/">
Saurabh Shukla
</a>
,
<a href="/name/nm0438463/">
Anil Kapoor
</a>
</p>
""" #The html code provided by you
soup = BeautifulSoup(html,'html5lib')
p_tag = soup.find('p')
span = p_tag.find('span',class_ = "ghost")
prev = list(span.previous_siblings) #Finds all the tags before the span tag with class ghost and converts them into a list
prev = [str(x) for x in prev]
prev = ''.join(prev) #Converts the list to a string
soup2 = BeautifulSoup(prev,'html5lib') #Creates a new BeautifulSoup object with the newly formed string
a_tags = soup2.find_all('a')
for a in a_tags:
txt = a.text.strip()
print(txt)
输出:
Loveleen Tandan
Danny Boyle
希望这会有所帮助!
推荐阅读
- python - 如何通过每次按向上箭头在 PyCharm 中运行“manage.py runserver”命令?
- reactjs - 在 Material UI 多选中添加全选并在选择选项中显示值
- r - 如何使用 R Shiny 中的绘图代理将文本注释添加到绘图图中
- scala - How to obtain all possible members of a coproduct
- typescript - 在 TypeScript 上投射地图值
- sql - SQL 返回最后日期
- node.js - 阻止来自 chrome、safari 和所有浏览器的 Aws cloudfront url 访问
- angular - Angular 9做同步调用,在做任何其他事情之前等待
- javascript - 错误:找不到模块“./util/eventLoader”
- java - 在持续交付代理上使用 jpackage 构建 Windows 安装程序