在 python 中从 html 抓取时,网站将我视为移动设备

Website Treating me as mobile when scraping from html in python

我正在尝试结合使用 urllib2 和 beautifulsoup 从网站上抓取数据。目前,这是我的代码:

site2='http://football.fantasysports.yahoo.com/archive/nfl/2008/619811/draftresults'
players=[]
teams=[]
response=urllib2.urlopen(site2)
html=response.read()
soup=BeautifulSoup(html)
playername = soup.find_all('a', class_="name")
teamname = soup.find_all('td', class_="last")

我的问题是,当我查看 Chrome 中的源代码时,这些标签随时可用并且可以正常工作,但是当我尝试 运行 程序时,标签不再存在.

一个提示可能是源代码的第一行是这样的: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 而如果我打印我的汤或 html 对象,第一行是 <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">。 当我尝试使用 urllib2 抓取它时,url 似乎以移动形式出现。如果这不是这个意思,或者您确实知道如何让 urllib2 作为浏览器(最好是 chrome)打开 url,请告诉我!也请非常具体地说明我如何解决这个问题,因为我是一个新手编码员,而且我的知识深度充其量是肤浅的!

谢谢大家!

该网站试图找出来自 'User-agent' 的请求来源的浏览器。根据 urllib2 docs,默认用户代理是 Python-urllib/2.6。您可以尝试使用 OpenerDirector 将其设置为浏览器的设置。同样,来自文档:

import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')