我正在尝试从中收集数据的网站是http://www.boxofficemojo.com/yearly/chart/?yr=2015&p=.htm。现在,我想在此页面上获得电影的所有标题,然后再移至每个链接中的其余数据(工作室等)和其他数据。这是我到目前为止所拥有的:
import requests
from bs4 import BeautifulSoup
from urllib2 import urlopen
def trade_spider(max_pages):
page = 0
while page <= max_pages:
url = 'http://www.boxofficemojo.com/yearly/chart/?page=' + str(page) + '&view=releasedate&view2=domestic&yr=2015&p=.htm'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll('a', {'div':'body'}):
href = 'http://www.boxofficemojo.com' + link.get('href')
title = link.string
print title
get_single_item_data(href)
page += 1
def get_single_item_data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for item_name in soup.findAll('section', {'id':'postingbody'}):
print item_name.text
trade_spider(1)
我遇到麻烦的是
for soup.findAll('a',{'div':'body'})中的链接:
href =' http ://www.boxofficemojo.com'+ link.get('href')
问题在于该网站上没有所有链接都属于其中的识别类。链接仅带有“ <ahref>”标签。
如何获得此页面上链接的所有标题?
一种可能的方法是使用.select()
接受CSS选择器参数的方法:
for link in soup.select('td > b > font > a[href^=/movies/?]'):
......
......
有关使用CSS选择器的简要说明:
td > b
:查找所有td
元素,然后从每个元素中td
查找直接子b
元素> font
:从过滤的b
元素中查找直接子font
元素> a[href^=/movies/?]
:从过滤的font
元素中返回a
具有href
属性值开头的直接子元素"/movies/?"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句