美文网首页大数据 爬虫Python AI SqlPython学习
用Python爬取豆瓣Top250的电影标题

用Python爬取豆瓣Top250的电影标题

作者: 1a076099f916 | 来源:发表于2019-01-23 15:30 被阅读3次
用Python爬取豆瓣Top250的电影标题

所以我们可以这么写去得到所有页面的链接

进群:700341555获取Python爬虫教程!

用Python爬取豆瓣Top250的电影标题 用Python爬取豆瓣Top250的电影标题 用Python爬取豆瓣Top250的电影标题

我们知道标题是在 target="_blank"> 标题的位置</a> 之中

所以可以通过正则表达式找到所有符合条件的标题

用Python爬取豆瓣Top250的电影标题

将内容写入到表格保存起来

用Python爬取豆瓣Top250的电影标题

下面贴入完整代码


import requests, bs4, re, openpyxl

url = 'https://www.douban.com/doulist/3936288/?start=%s'

urls = []

多少页

pages = 10

for i in range(pages):

urls.append(url%(i*25)) #得到所有页面的链接(共10页)

存储标题的数组

titles = []

urlElems = []

for index in range(pages):

res = requests.get(urls[index]) #每一页的链接

html_doc=str(res.content,'utf-8') #得到链接里面的内容,转换编码

soup = bs4.BeautifulSoup(html_doc, 'html.parser')

urlElems.extend(soup.select('.title a')) #得到所有 title类 下面的 a 标签(标题的位置)

try:

res.raise_for_status() #下载失败就抛异常

except Exception as exc:

print('There is was a problem: %s' %(exc))

for i in range(len(urlElems)):

将得到的标题保存在数组里面

titles.extend(re.findall(re.compile('''target="_blank">

(.*?)[

</a>]'''),str(urlElems[i])))

wb = openpyxl.Workbook()

sheet = wb.get_active_sheet()

for i in range(len(titles)):

将标题写入表格中

sheet.cell(row = i+1, column = 1).value= titles[i]

wb.save('豆瓣top250.xlsx')#保存表格

print('OK')


大家可以举一反三,去爬取其它网站上面自己想要的内容~~~

相关文章

网友评论

    本文标题:用Python爬取豆瓣Top250的电影标题

    本文链接:https://www.haomeiwen.com/subject/klzjjqtx.html