【问题标题】:why my Beautiful Soup not getting query strings of links?为什么我的 Beautiful Soup 没有得到链接的查询字符串?
【发布时间】:2020-04-04 09:54:30
【问题描述】:

我正在尝试通过 BeautifulSoup 获取锚标记的 href,但它不检索查询字符串! 这是 html sn-p:

<td class="titleColumn">
  143.
  <a href="/title/tt1302006/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=e31d89dd-322d-4646-8962- 
  327b42fe94b1&pf_rd_r=0GYQY7SGFV9AK9CV3019&pf_rd_s=center- 
  1&pf_rd_t=15506&pf_rd_i=top&ref_=chttp_tt_143"
  title="Martin Scorsese (dir.), Robert De Niro, Al Pacino" >The Irishman</a>
    <span class="secondaryInfo">(2019)</span>
</td>

这是soup返回的链接:

https://www.imdb.com/chart/top/?sort=us,desc&mode=simple&page=1/title/tt1302006/

这是我的代码:

import requests
from bs4 import BeautifulSoup
add="https://www.imdb.com/chart/top/?sort=us,desc&mode=simple&page=1"
r = requests.get(add)
soup = BeautifulSoup(r.text)
i=1;
for movie in soup.find_all("td",{"class":"titleColumn"}):
    print (add+movie.find('a')['href'])

soup 中的链接也没有查询字符串

【问题讨论】:

  • 您确定查询字符串在 HTML 中,而不是 JavaScript 之后添加的吗?
  • 这不是问题,但感谢您的关注
  • 首先,如果结果是 HTML 或 XML(以及其他),请使用 r.content 而不是 r.text。其次,它不检索查询字符串究竟是什么意思?它只返回一个字符串,这也恰好是错误的? 汤里的链接也没有查询字符串是什么意思?
  • 这与请求有关,我已尝试使用 cURL,更改用户代理并使用 urllib,但原始 HTML 不会像他所说的那样显示查询变量。

标签: python beautifulsoup


【解决方案1】:

如果您不定义用户代理,有时 Web 服务器会做出不同的响应。单击以下链接以了解有关用户代理的更多信息。

https://www.howtogeek.com/114937/htg-explains-whats-a-browser-user-agent/

这是在代码中定义用户代理标头的方法。

import requests
from bs4 import BeautifulSoup
add="https://www.imdb.com/chart/top/?sort=us,desc&mode=simple&page=1"
r = requests.get(add, headers = {'User-Agent': "user-agent"})
soup = BeautifulSoup(r.text)
i=1;
for movie in soup.find_all("td",{"class":"titleColumn"}):
    print (add+movie.find('a')['href'])

【讨论】:

  • 尝试将“user-agent”字符串替换为另一个字符串,即“Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0”
  • 这是正确的解释,但您必须使用真实浏览器发送的用户代理。从浏览器控制台复制navigator.userAgent 的值。
【解决方案2】:

试试这个

import requests
from bs4 import BeautifulSoup
user-agent = 'valid user agent'  #enter a valid user agent here
add="https://www.imdb.com/chart/top/?sort=us,desc&mode=simple&page=1"
r = requests.get(add, headers = {'User-Agent': user-agent})
soup = BeautifulSoup(r.content)
i=1;
for movie in soup.find_all("td",{"class":"titleColumn"}):
    print (add+movie.find('a')['href'])

注意我使用的是 r.content 而不是 r.text。我还发现有时在这些情况下使用有效的用户代理真的很有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多