我尝试爬网的页面是http://www.boxofficemojo.com/yearly/chart/?page=1&view=releasedate&view2=domestic&yr=2013&p=.htm。具体来说,我现在专注于此页面:http://www.boxofficemojo.com/movies/?id=ironman3.htm。
对于第一个链接上的每部电影,我想获取类型,运行时间,MPAA评分,外国总收入和预算。我遇到了麻烦,因为信息上没有识别标签。到目前为止,我有:
import requests
from bs4 import BeautifulSoup
from urllib2 import urlopen
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://www.boxofficemojo.com/yearly/chart/?page=' + str(page) + '&view=releasedate&view2=domestic&yr=2013&p=.htm'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.select('td > b > font > a[href^=/movies/?]'):
href = 'http://www.boxofficemojo.com' + link.get('href')
title = link.string
print title, href
get_single_item_data(href)
def get_single_item_data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
print soup.find_all("Genre: ")
for person in soup.select('td > font > a[href^=/people/]'):
print person.string
trade_spider(1)
到目前为止,这将从原始页面中检索电影的所有标题,它们的链接以及每个电影的演员/人物/导演等的列表。现在,我正在尝试了解电影的类型。
我尝试以与
"for person in soup.select('td > font > a[href^=/people/]'):
print person.string"
行,但这不是链接,它只是文本,因此不起作用。
如何获得每部电影的数据?
最佳答案
找到Genre:
文本并获得next sibling:
soup.find(text="Genre: ").next_sibling.text
演示:
In [1]: import requests
In [2]: from bs4 import BeautifulSoup
In [3]: response = requests.get("http://www.boxofficemojo.com/movies/?id=ironman3.htm")
In [4]: soup = BeautifulSoup(response.content)
In [5]: soup.find(text="Genre: ").next_sibling.text
Out[5]: u'Action / Adventure'
关于python - BeautifulSoup Web爬网:如何获取文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31035973/