博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python网络爬虫--BeautifulSoup提取猫眼TOP100电影
阅读量:4346 次
发布时间:2019-06-07

本文共 1890 字,大约阅读时间需要 6 分钟。

import requestsfrom bs4 import BeautifulSoupimport bs4import reimport jsondef getPage(url):    try:        headers = {    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"    }        response = requests.get(url,headers = headers)        if response.status_code == 200:            response.encoding = "UTF-8"            return response.text    except requests.ConnectionError:      return Nonedef parsePage(html):    soup = BeautifulSoup(html,"html.parser")    for child in soup.find("dl").children:        if isinstance(child,bs4.element.Tag):            index = child.find(class_ = re.compile("^board-index")) #提取电影排名            title = child.find(class_ = "name") # 提取电影名称,此处用的时标签属性,还有其它的方法,比如说CSS。 child.select(".name")            releasetime = child.find(class_ ="releasetime") # 提取上映时间            actor = child.find(class_ = "star")  # 提取主演            score = child.find(class_ = "score") # 提取评分            totalScore = ""            for sco in score:                totalScore = totalScore + sco.string            imageLink = child.find(class_ = "board-img") # 提取电影封面链接            yield{            "index":index.string,            "imageLink":imageLink["data-src"],            "title":title.string,            "releasetime":releasetime.string.strip()[5:],            "actor":actor.string.strip()[3:],            "score":totalScore            }                    def writeInfomation(content):    with open("Movie BeautifulSoup.text","a") as f:        f.write(json.dumps(content,ensure_ascii = False)+"\n")        def main(offset):    url = "https://maoyan.com/board/4?offset="+str(offset)    html = getPage(url)    for item in parsePage(html):        writeInfomation(item)if __name__ == "__main__":    for i in range(10):        main(offset = i*10)

 

转载于:https://www.cnblogs.com/sakura-d/p/10911509.html

你可能感兴趣的文章
SQL 笔记
查看>>
浅析Staging
查看>>
Unity倒计时动画
查看>>
rem布局
查看>>
Windows server 2008 R2配置多个远程连接的教程
查看>>
PHP 重置数组为连续数字索引的几种方式
查看>>
南阳理工acm 88-汉诺塔(一)
查看>>
160809308周子济第六次作业
查看>>
大型Web应用运行时 PHP负载均衡指南
查看>>
为phpStorm 配置PHP_CodeSniffer自动检查代码
查看>>
软件cs页面分辨率测试
查看>>
random 模块
查看>>
2.点线面
查看>>
一个js的工具类
查看>>
Java解析Excel
查看>>
68 聚合和分组, F和Q查询, cookie, session
查看>>
Python的subprocess模块
查看>>
struts2的 result 通配符 OGNL
查看>>
[Arduino] 逗号分隔文本到数组的两种方法
查看>>
jq动画效果
查看>>