首页 > 解决方案 > 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。

预先感谢您提出任何可能解决此问题的建议。

标签: pythonbeautifulsouppython-requests

解决方案


由于使用了商业 IP,您可能会点击域的验证码服务或其他过滤器。请求您尝试抓取的页面,将其保存到文件中,然后检查网络服务器发送给您的内容。您也可以将r.status_code其用作故障排除的一部分。


推荐阅读