Python 3 웹 스크랩에서 HTTP 오류 403
연습을 위해 웹 사이트를 스크랩하려고했지만 HTTP 오류 403이 계속 발생합니까 (내가 봇이라고 생각합니까?)?
내 코드는 다음과 같습니다.
#import requests
import urllib.request
from bs4 import BeautifulSoup
#from urllib import urlopen
import re
webpage = urllib.request.urlopen('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1').read
findrows = re.compile('<tr class="- banding(?:On|Off)>(.*?)</tr>')
findlink = re.compile('<a href =">(.*)</a>')
row_array = re.findall(findrows, webpage)
links = re.finall(findlink, webpate)
print(len(row_array))
iterator = []
내가 얻는 오류는 다음과 같습니다.
File "C:\Python33\lib\urllib\request.py", line 160, in urlopen
return opener.open(url, data, timeout)
File "C:\Python33\lib\urllib\request.py", line 479, in open
response = meth(req, response)
File "C:\Python33\lib\urllib\request.py", line 591, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python33\lib\urllib\request.py", line 517, in error
return self._call_chain(*args)
File "C:\Python33\lib\urllib\request.py", line 451, in _call_chain
result = func(*args)
File "C:\Python33\lib\urllib\request.py", line 599, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
이것은 아마도 때문이다 mod_security
(블록 거미 / 봇 사용자 에이전트 알려진 몇 가지 유사한 서버 보안 기능 또는 urllib
같이 사용 무언가 python urllib/3.3.0
그것을 쉽게 감지 것). 다음을 사용하여 알려진 브라우저 사용자 에이전트를 설정해보십시오.
from urllib.request import Request, urlopen
req = Request('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
이것은 나를 위해 작동합니다.
그건 그렇고, 당신의 코드에서 당신은 누락 ()
후 .read
의 urlopen
라인,하지만 난 그게 오타가 있다고 생각합니다.
팁 : 이것은 운동이므로 제한되지 않는 다른 사이트를 선택하십시오. urllib
왠지 막고 있을지도 ...
사용자 에이전트를 기반으로 urllib를 사용하기 때문에 확실히 차단됩니다. OfferUp에서도 이와 동일한 일이 발생합니다. Mozilla로 사용자 에이전트를 재정의하는 AppURLopener라는 새 클래스를 만들 수 있습니다.
import urllib.request
class AppURLopener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
opener = AppURLopener()
response = opener.open('http://httpbin.org/user-agent')
"이것은 아마도 mod_security 또는 알려진 것을 차단하는 유사한 서버 보안 기능 때문일 것입니다.
거미 / 봇
사용자 에이전트 (urllib는 python urllib / 3.3.0과 같은 것을 사용하며 쉽게 감지 됨) "-이미 Stefano Sanfilippo에서 언급했듯이
from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
web_byte는 서버와 웹 페이지의 콘텐츠 형식 존재에 의해 반환 된 바이트 객체 인 대부분이다 UTF-8 . 따라서 디코딩 방법을 사용하여 web_byte 를 디코딩 해야합니다 .
이것은 PyCharm을 사용하여 웹 사이트에서 스크랩을 시도하는 동안 완전한 문제를 해결합니다.
P.S -> I use python 3.4
Since the page works in browser and not when calling within python program, it seems that the web app that serves that url recognizes that you request the content not by the browser.
Demonstration:
curl --dump-header r.txt http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1
...
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
You don't have permission to access ...
</HTML>
and the content in r.txt has status line:
HTTP/1.1 403 Forbidden
Try posting header 'User-Agent' which fakes web client.
NOTE: The page contains Ajax call that creates the table you probably want to parse. You'll need to check the javascript logic of the page or simply using browser debugger (like Firebug / Net tab) to see which url you need to call to get the table's content.
You can try in two ways. The detail is in this link.
1) Via pip
pip install --upgrade certifi
2) If it doesn't work, try to run a Cerificates.command that comes bundled with Python 3.* for Mac:(Go to your python installation location and double click the file)
open /Applications/Python\ 3.*/Install\ Certificates.command
참고URL : https://stackoverflow.com/questions/16627227/http-error-403-in-python-3-web-scraping
'IT TIP' 카테고리의 다른 글
최대 횟수까지 무언가를 시도하는 비단뱀적인 방법이 있습니까? (0) | 2020.10.15 |
---|---|
서로를 참조하는 불변 객체? (0) | 2020.10.15 |
Go에서 테스트 패키지를 사용하여 테스트 설정을 수행하려면 어떻게해야합니까? (0) | 2020.10.15 |
현재 선택된 항목을 유지하면서 Html Select의 옵션을 값별로 정렬하는 가장 효율적인 방법은 무엇입니까? (0) | 2020.10.15 |
DB의 모든 테이블, 행 및 열에서 문자열 검색 (0) | 2020.10.15 |