无法使用python beautifulsoup获取项

2024-05-12 21:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习如何使用beauthoulsoup+python进行web垃圾搜索,我想从https://letterboxd.com/film/donnie-darko/中获取电影摄影师的名字,但我不知道如何隔离文本。我想要的html是这样写的,我想输出的是“Steven Poster”:

<h3><span>Cinematography</span></h3>
<div class="text-sluglist">
    <p>
        <a href="/cinematography/steven-poster/" class="text-slug">Steven Poster</a> 
    </p>
</div>

在我的代码范围内我已经做到了汤。找(text=“Cinemaography”),以及各种不同的东西的混合,比如试图从a和p标记中找到项目或获取_文本,但是。。。在


Tags: texthttps文本divcomwebh3class
3条回答

我将使用正则表达式来解析soup对象以获取包含“电影摄影”的链接。在

import re
import requests
from bs4 import BeautifulSoup

r = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(r.text, 'lxml')
cinematographer = soup(href=re.compile(r'/cinematography/'))[0].text

print cinematographer
# outputs "Stephen Poster"

使用CSS部分文本选择器:

soup.find('a[href*="cinematography"]').text

也可以在不使用regex的情况下执行相同的操作:

import requests
from bs4 import BeautifulSoup

res = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(res.text,'lxml')
item = soup.select("[href*='cinematography']")[0].text
print(item)

输出:

^{pr2}$

相关问题 更多 >