我正试图从http://fortune.com/fortune500获取公司信息以获取我的论文。当我从链接下载web_text时,没有用于解析的链接。但是,在Chrome上打开链接会自动转到#1公司页面。
有人可以帮助向我解释发生了什么以及如何从原始网址跟踪公司页面的链接?
答案 0 :(得分:2)
首先,您需要获取postid
,然后向/data/franchise-list
发出请求,然后从第一篇文章中获取网址:
import json
import re
from urllib2 import urlopen
from urlparse import urljoin
from bs4 import BeautifulSoup
data = urlopen('http://fortune.com/fortune500/')
soup = BeautifulSoup(data)
postid = next(attr for attr in soup.body['class'] if attr.startswith('postid'))
postid = re.match(r'postid-(\d+)', postid).group(1)
url = "http://fortune.com/data/franchise-list/{postid}/1/".format(postid=postid)
data = json.load(urlopen(url))
resulting_url = urljoin(url, data['articles'][0]['url'])
print resulting_url
打印:
http://fortune.com/fortune500/wal-mart-stores-inc-1/