【问题标题】:Cannot Retrieve contents of a page using BeautifulSoup无法使用 BeautifulSoup 检索页面的内容
【发布时间】:2018-12-22 12:25:23
【问题描述】:

我正在学习 BeautifulSoup 并尝试加载 this 网页的内容。我试图通过inspect element 深入了解HTML tags 来获取内容。

我使用不同的代码sn-ps来显示并检查我是否能够成功检索到内容。

以下代码 sn-ps 产生了很好的结果:

from bs4 import BeautifulSoup
import requests

root = 'https://www.quora.com/topic/Graduate-Record-Examination-GRE-1'
r = requests.get(root)

soup = BeautifulSoup(r.text,'html.parser')

#**The following worked yielded some results :**

#1
a = soup.find_all('div',{'class':'feed'})
print(a)

#2
b = soup.find_all('div',{'class':'ContentWrapper'})
print(b)

#3
c = soup.find_all('div',{'class':'ContentWrapper'})
print(c)

#4
d = soup.find_all('div',{'class':'feed'})
print(d)

#5
e = soup.find_all('div',{'class':'TopicFeed'})
print(e)

但是,在深入了解之后,以下内容并没有产生任何结果:

f = soup.find_all('div',{'class':'paged_list_wrapper'})
print(f)

打印:[]

<div class='paged_list_wrapper'> 内的内容/HTML 代码未打印。为什么?

【问题讨论】:

  • 我确实通过soup.find_all('div',{'class':'paged_list_wrapper'}) 获取信息。您确定要查看共享链接的响应吗?

标签: python html web-scraping beautifulsoup quora


【解决方案1】:

站点可以配置为根据用户代理发送不同的页面。我遇到了和你一样的问题。它返回一个空列表。在标题中添加一个通用用户代理为我解决了这个问题。

from bs4 import BeautifulSoup
import requests
root = 'https://www.quora.com/topic/Graduate-Record-Examination-GRE-1'
headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.' }
r = requests.get(root,headers=headers)
soup = BeautifulSoup(r.text,'html.parser')
f = soup.findAll('div',{'class':'paged_list_wrapper'})
print(f)

【讨论】:

  • 在上述情况下,generic user agent 是做什么的?
  • @rahul 您必须使用类似于您用于查找 div 类的用户代理。如果您是通过智能手机等设备访问该页面,则站点源可能没有该特定类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2020-01-04
  • 2021-12-07
  • 1970-01-01
相关资源
最近更新 更多