允许请求使用Python重定向以读取webpage

2024-10-01 19:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python加载网站并读取它们的可见文本,但是我列表中的一些站点无法正确加载,因为它们没有成功地重定向到主网站页面。e、 g.网址imfuna.com网站应重定向到imfuna.com/home-但是它没有,因此我的代码只检索6个单词,而不是它应该检索的64个单词。在

import requests
from bs4 import BeautifulSoup

# error handling

from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# settings

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}

url = "http://imfuna.com"

response = requests.get(url, headers=headers, verify=False)

soup = BeautifulSoup(response.text, "lxml")

for script in soup(["script", "style"]):
    script.extract()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
text = '\n'.join(chunk for chunk in chunks if chunk)

front_text_count = len(text.split(" "))
print front_text_count
print text

如果你运行这个,你只得到6个单词:

^{pr2}$

但实际上你应该得到64(浏览器重定向到http://imfuna.com/home-uk/并在那里看到内容)。在

任何人都知道我如何设置请求以允许重定向发生,而不是解析位于http://imfuna.com/home-uk/的页面

谢谢:)


Tags: textinimportcomhttphomefor网站

热门问题