python - Python - 请求 - BeatuifulSoup - 在本地运行脚本时找到 HTML 但在 VPS 上运行时找不到
问题描述
当我尝试运行一个应该使用 Beautifulsoup 从 URL 的 HTML 输出事件名称的基本测试脚本时,我遇到了一个奇怪的问题。#
代码如下:
import requests
import time
from bs4 import BeautifulSoup
def makesoup(url):
cookies = {'mycountries' : '101,28,3,102,42,10,18,4,2,22', 'user_time_zone': 'Europe/London', 'user_time_zone_id': '1'}
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r = requests.post(url, headers=headers, cookies=cookies)
return BeautifulSoup(r.text,"html.parser")
def linkscrape(links, savefile):
baseurl = "https://sport-tv-guide.live"
urllist = []
for link in links:
finalurl = (baseurl+ link['href'])
urllist.append(finalurl)
print(finalurl)
for singleurl in urllist:
soup2=makesoup(url=singleurl)
g_data=soup2.find_all('div', {'id': 'channelInfo'})
for match in g_data:
print(g_data)
try:
event = match.find('div', class_='title full').text.strip()
print(event)
except:
event = ""
def matches():
dict = {"https://sport-tv-guide.live/live/boxing":"/var/scripts/output/boxing.txt"}
for key, value in dict.items():
soup=makesoup(url=key)
game_check = soup.find('div', class_='alert alert-info')
if game_check is not None:
with open(value ,"w") as text_file:
text_file.writelines("No games found for event")
else:
linkscrape(links=soup.find_all('a', {'class': 'article flag', 'href': True}), savefile = value)
matches()
当我在本地运行代码时,我收到以下输出:
当我在我的 VPS 服务器上运行完全相同的代码时,我会收到以下输出:
起初我在想网站阻止了基于用户代理的请求,所以我在上面的代码中添加了标头,但问题仍然存在。我能想到的唯一另一件事是该站点阻止了 VPS 服务器的 IP,虽然奇怪的是它正在打印出正确的 URL,但是当我使用时,Beautifulsoup 没有输出/找到 URL 的 HTML一个VPS。
预先感谢您提出任何可能解决此问题的建议。
解决方案
由于使用了商业 IP,您可能会点击域的验证码服务或其他过滤器。请求您尝试抓取的页面,将其保存到文件中,然后检查网络服务器发送给您的内容。您也可以将r.status_code
其用作故障排除的一部分。
推荐阅读
- django - (Django) 显示有关模型实例的简单统计信息
- python - python线程start_new_thread和使用celery的区别,哪个对django的异步任务有好处
- python - 如何在 PyQT4 表格视图中突出显示每行中值最高的单元格
- php - PHP Symfony Finder:按目录深度排序
- python - 为什么没有事先分配的下一个函数不能在 Iterator 对象上工作?
- python - Selenium Django-Python with Chrome,我找不到带有 xpath 的元素 - 表单的 NoSuchElementException
- python - 从派生类对象python调用基类的方法
- sulu - 如何在块内容类型中使用复选框内容类型以及如何从 Sulu-minimal 中的块内容类型中获取复选框的值?
- android - 预期开始数组,但开始对象
- c - 有没有办法在找到句点 (.) 之前读取文件流。然后重复?