【问题标题】:Python3, beautifulsoup, return nothing in specific pagesPython3,beautifulsoup,特定页面不返回任何内容
【发布时间】:2018-02-15 18:39:56
【问题描述】:
在某些页面中,当我使用 beautifulsoup 时,什么都不返回……只是空白页面。
from bs4 import BeautifulSoup
import urllib.request
Site = "http://gall.dcinside.com/board/lists/?id=parkbogum&page=2"
URL = Site
html = urllib.request.urlopen(URL).read()
soup = BeautifulSoup(html, "html.parser")
print(soup)
我可以在除本网站之外的任何其他网站上使用 beautifulsoup。而且我不知道方法...
【问题讨论】:
标签:
python
python-3.x
beautifulsoup
urllib
【解决方案1】:
如我所见,该网站正在使用 cookie。您可以在浏览器的开发者工具中看到标题。您可以通过以下方式获取cookie:
import urllib.request
r = urllib.request.urlopen(URL)
ck = r.getheader('Set-Cookie')
现在您可以像这样创建标头并将其与后续请求一起发送。
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Cookie": ck,
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"
}
req = urllib.request.Request(URL, headers=headers)
html = urllib.request.urlopen(req).read()
【解决方案2】:
一些网站服务器会寻找试图访问其网页的机器人脚本。执行此操作的一种更简单的方法是检查浏览器正在发送哪个User-Agent。在这种情况下,由于您使用的是 Python 而不是 Web 浏览器,因此将发送以下内容:
python-requests/2.18.4
当它看到它不喜欢的代理时,它不会返回任何内容。要解决此问题,您需要更改请求中的 User-Agent 字符串。有数百种可供选择,因为代理字符串会随着浏览器的每个版本而变化。例如,请参阅Firefox User-Agent strings 的此列表,例如
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1
Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0
诀窍是尝试几个,然后找到一个服务器满意的。在您的情况下,只需要更改标题才能从网站返回 HTML。在某些情况下,还需要使用 cookie。
可以通过传递字典轻松更改标题。这可以使用requests 来完成,如下所示:
from bs4 import BeautifulSoup
import requests
url = "http://gall.dcinside.com/board/lists/?id=parkbogum&page=2"
html = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405'}).content
soup = BeautifulSoup(html, "html.parser")
print(soup)
【解决方案3】:
此 URL 需要在请求时传递某些标头。
在请求 URL 时传递此 headers 参数,您将获得 HTML。
HTML = requests.get(URL , headers = headers).content
同时
headers = {
"method":"GET",
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
"Host":"gall.dcinside.com",
"Pragma":"no-cache",
"Upgrade-Insecure-Requests":"1",
"Accept":"text/html,application/xhtml+xml,
application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
}