题目:
获取豆瓣TOP250电影的中英文名、港台名、导演、上映年份、电影分类以及评分,将数据存入文档。
代码:
import codecsimport csvimport refrom requests_html import HTMLSessionbase_url = "/top250?start="# 获取请求对象session = HTMLSession()result_list = []def filter(s):if s:s = s.strip()s = re.sub('\s+', ' ', s)s = s.replace(" / ", "/")if s[0] == "/":s = s[1:]s = s.strip()return sfor i in range(0, 10):url = base_url + str(i * 25)response = session.get(url)html = response.htmldiv = html.xpath('//*[@class="grid_view"]', first=True)div_list = div.xpath('//li')for d in div_list:z_name = filter(d.xpath('//div/div[2]/div[1]/a/span[1]/text()', first=True))e_name = filter(d.xpath('//div/div[2]/div[1]/a/span[2]/text()', first=True))g_name = filter(d.xpath('//div/div[2]/div[1]/a/span[3]/text()', first=True))info_list = d.xpath('//div/div[2]/div[2]/p/text()')# 省略部分代码,回复获取else:print(url, z_name, info_list)csv_file = codecs.open('data/movie_test.csv', 'w', encoding='utf-8')writer = csv.writer(csv_file)for d in result_list:writer.writerow((d['中文名'], d['英文名'], d['港台名'], d['导演'], d['上映年份'], d['分类'], d['评分']))csv_file.close()
输出结果:
python 网络爬虫 1.2 获取豆瓣TOP250电影的中英文名 港台名 导演 上映年份 电影分类以及评分 将数据存入文档。