gpt4 book ai didi

python - 为什么找不到元素 'a' ?

转载 作者:行者123 更新时间:2023-12-01 07:02:28 24 4
gpt4 key购买 nike

获取“div”元素,但以同样的方式获取“a”元素。

import requests
from bs4 import BeautifulSoup as bf

# link :
url = "https://www.imdb.com/search/name/?gender=male,female&ref_=nv_tp_cel"


Response = requests.get(url)

soup = bf(Response.text,'lxml')

div = soup.find_all('div', class_ = "lister-item-content")


a_tag = div.find_all('a')

print(a_tag)

我想打印“div”元素中的所有“a”元素。

最佳答案

迭代每个 div 元素,然后使用 div.findChildren 迭代每个 a 子元素:

import requests
from bs4 import BeautifulSoup as bf

# link :
url = "https://www.imdb.com/search/name/?gender=male,female&ref_=nv_tp_cel"


Response = requests.get(url)

soup = bf(Response.text,'lxml')

divs = soup.find_all('div', class_ = "lister-item-content")

for div in divs:
a_tags = div.findChildren('a')

for a_tag in a_tags:
print (a_tag)

这会打印出类似的内容:

...
<a href="/title/tt0356910/"> Mr. &amp; Mrs. Smith
</a>
<a href="/title/tt0137523">Fight Club</a>
<a href="/title/tt1210166">Moneyball</a>
<a href="/title/tt0240772">Ocean's Eleven</a>
<a href="/name/nm0000522"> Vanessa Marcil
</a>
<a href="/title/tt0117500/"> The Rock
</a>

关于python - 为什么找不到元素 'a' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58577237/

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