漂亮的汤不拉网页的所有html

2024-09-24 00:22:43 发布

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

我试着练习使用BeautifulSoup。我正试图从这个网站上提取足球运动员的图片地址:https://www.transfermarkt.com/jordon-ibe/profil/spieler/195652

当我“inspect”代码时,包含imgsrc的部分如下:

    <div class="dataBild">
    <img src="https://tmssl.akamaized.net//images/portrait/header/195652-1456301478.jpg?lm=1456301501" title="Jordon Ibe" alt="Jordon Ibe" class="">
<div class="bildquelle"><span title="imago">imago</span></div>            
</div>

所以我想我可以用BeautifulSoup来找到div和{}的,因为这是唯一的。在

^{pr2}$

这会运行,但不会输出任何内容。所以我只需运行print(soup)

# Import the Libraries that I need
import urllib3
import certifi
from bs4 import BeautifulSoup

# Specify the URL
url = 'https://www.transfermarkt.com/jordon-ibe/profil/spieler/195652'
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
response = http.request('GET', url)


#Parse the html using beautiful soup and store in variable 'soup'
soup = BeautifulSoup(response.data, "html.parser")

print(soup)

这个输出

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr/><center>nginx</center>
</body>
</html>

所以它显然没有从网页上提取所有的HTML? 为什么会这样?我寻找div class = DataBild sound的逻辑是什么?在


Tags: thehttpsimportdivcomtitlehtmlwww
1条回答
网友
1楼 · 发布于 2024-09-24 00:22:43

站点似乎在检查请求的User-Agent头是否有效。在

所以你需要像这样添加标题:

import urllib3
import certifi

url = 'https://www.transfermarkt.com/jordon-ibe/profil/spieler/195652'
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
response = http.request('GET', url, headers={'User-Agent': 'Mozilla/5.0'})
print(response.status)

这将打印200。如果删除标题,则得到404。在

任何非空的User-Agent值(在修剪空白之后)似乎都可以工作。在

相关问题 更多 >