BeautifulSoup Webscraping错误

时间:2018-04-27 14:00:00

标签: python web-scraping beautifulsoup

我正在尝试网站抓取网站,我不断收到以下错误消息。我在其他网站上尝试过这个脚本,它运行正常。我已经搜索过找到一个解决方案,似乎无法找到一个有效的解决方案。 Traceback (most recent call last): File "math-webscrape.py", line 8, in <module> uClient = urlopen(math_url) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 532, in open response = meth(req, response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 570, in error return self._call_chain(*args) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden

这是我的剧本

from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
import json

math_url = 'https://aimath.org/textbooks/approved-textbooks/'

#opening up connection and grabbing page
uClient = urlopen(math_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

#grabs info for each textbook
containers = page_soup.findAll("p",{"class":"approved-book"})

data = []
for container in containers:
item = {}
item['type'] = "Textbook"
item['title'] = container.a.text
item['author'] =container.a.findNextSibling(text=True).strip()
item['link'] = container.a["href"]
item['source'] = "College Open Textbooks"
data.append(item) # add the item to the list

with open("./json/cot.json", "w") as writeJSON:
   json.dump(data, writeJSON, ensure_ascii=False)

3 个答案:

答案 0 :(得分:0)

目标网站显然阻止了urllib的用户代理。

您可以设置自定义用户代理以绕过此问题:How do I send a custom header with urllib2 in a HTTP Request?

答案 1 :(得分:0)

这个网站似乎阻止了默认的python User-Agent。你可以像这样伪装自己:

import urllib.request

math_url = 'https://aimath.org/textbooks/approved-textbooks/'

req = urllib.request.Request(
    math_url, 
    data=None, 
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    }
)

uClient = urllib.request.urlopen(req)

答案 2 :(得分:0)

您需要使用标头来获取响应。您可以尝试如下:

from urllib.request import urlopen, Request

math_url = 'https://aimath.org/textbooks/approved-textbooks/'

res = Request(math_url,headers={"User-Agent":"Mozilla/5.0"})
uClient = urlopen(res)
page_html = uClient.read()