我在尝试从网页获取html内容时遇到问题。
在该网站中:https://tmofans.com/library/manga/5763/nisekoi单击“ Capitulo 230.00”中的考验播放图标时,打开下一个链接:https://tmofans.com/goto/347231将您重定向到该网站:https://tmofans.com/viewer/5c187dcea0240/paginated
问题是当您直接在以下链接上打开时:https://tmofans.com/goto/347231,该页面显示403 Forbidden消息。 重定向到最后一页的唯一方法是单击首页上的播放按钮。
我只想使用tmofans.com/goto链接获得最终的url内容
我试图使用请求和BeautifulSoup获取html内容
import requests
from BeautifulSoup import BeautifulSoup
response = requests.get("https://tmofans.com/goto/347231")
page = str(BeautifulSoup(response.content))
print page
当我使用https://tmofans.com/goto/347231执行此操作时,我仅获得403禁止页面的内容。
答案 0 :(得分:1)
此网站检查您的站点是否有推荐人,否则给您403答复。您可以通过设置引荐来源网址轻松地绕过此操作。
import requests
ref='https://tmofans.com'
headers = { 'Referer': ref }
r = requests.get('https://tmofans.com/goto/347231',headers=headers)
print(r.url)
print(r.status_code)
输出
https://tmofans.com/viewer/5c187dcea0240/paginated
200
答案 1 :(得分:0)
我曾经设法使用http.client
和我的浏览器来抓取一些受保护的页面。
我首先导航到需要访问的页面,然后使用浏览器的开发人员工具复制了 request 标头,并在脚本中使用了它们。这样,您的脚本将以与浏览器相同的方式访问资源。
这两种方法可以为您提供帮助,首先解析HTTP请求以获取标头(请求和正文 可能会有所帮助,具体取决于您的情况),然后使用第二种方法下载文件。 / p>
这可能需要您进行一些调整才能起作用。
from http.client import HTTPSConnection
def parse_headers(http_post):
"""Converts a header string to a dictionnary of its attributes."""
# Regex to extract headers
req_line = re.compile(r'(?P<method>GET|POST)\s+(?P<resource>.+?)\s+(?P<version>HTTP/1.1)')
field_line = re.compile(r'\s*(?P<key>.+\S)\s*:\s+(?P<value>.+\S)\s*')
first_line_end = http_post.find('\n')
headers_end = http_post.find('\n\n')
request = req_line.match(http_post[:first_line_end]).groupdict()
headers = dict(field_line.findall(http_post[first_line_end:headers_end]))
body = http_post[headers_end + 2:]
return request, headers, body
def get_file(url, domain, headers, temp_directory):
"""
Fetches the file located at the provided URL and returns the content.
Uses `headers` to bypass auth.
"""
conn = HTTPSConnection(domain)
conn.request('GET', url, headers=headers)
response = conn.getresponse()
content_type = response.getheader('Content-Type')
content_disp = response.getheader('Content-Disposition')
# Change to whatever content type you need
if content_type != 'application/pdf':
conn.close()
return
else:
file_content = response.read()
conn.close()
return file_content
标头字符串应如下所示:
GET /fr/backend/XXXXXXXXX/845080 HTTP/1.1
Cookie: cookie_law_consented=true; landing_page=0; _ga=GA1.2.1218703015.1546948765; _gid=GA1.2.580320014.1546948765; _jt=1.735724042.1546948764; SID=5c485bfa-3f2c-425e-a2dd-32dd800e0bb3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: br, gzip, deflate
Host: XXXXX
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15
Accept-Language: fr-fr
Referer: XXXXX
Connection: keep-alive
它可能会因网站而异,但是使用这些文件,我可以在登录后下载文件。