python3.6抓取出现TypeError: cannot use a string pattern on a bytes-like object

简介:
import re
import requests
from requests.exceptions import RequestException
import json


def get_one_page(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.content
return None
except RequestException:
return None


def parse_page_html(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)

items = re.findall(pattern, html)
for item in items:
yield {
'index':item[0],
'image':item[1],
'title':item[2],
'actor':item[3].strip()[3:],
'time':item[4].strip()[5:],
'score':item[5]+item[6]
}

def write_to_file(content):
with open('result.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n')
f.close()

def main():
url = 'http://maoyan.com/board/4?'
html = get_one_page(url)
for item in parse_page_html(html):
write_to_file(item)


if __name__ == '__main__':
main()



如果没有以上红色代码,会出现TypeError: cannot use a string pattern on a bytes-like object,只需要加上html = html.decode('utf-8')即可

目录
相关文章
|
1月前
|
存储 缓存 Python
如何使用Python抓取PDF文件并自动下载到本地
如何使用Python抓取PDF文件并自动下载到本地
34 0
|
2月前
|
数据采集 前端开发 JavaScript
利用 Python 抓取数据探索汽车市场趋势
利用 Python 抓取数据探索汽车市场趋势
|
2月前
|
数据采集 数据可视化 数据挖掘
Python爬虫实战:抓取网站数据并生成报表
本文将介绍如何使用Python编写简单而高效的网络爬虫,从指定的网站上抓取数据,并利用数据分析库生成可视化报表。通过学习本文内容,读者将能够掌握基本的爬虫技术和数据处理方法,为日后开发更复杂的数据采集与分析工具打下坚实基础。
|
1月前
|
Java 测试技术 数据库
hql投影查询之—— [Ljava.lang.Object; cannot be cast to cn.bdqn.guanMingSys.entity.Notice
hql投影查询之—— [Ljava.lang.Object; cannot be cast to cn.bdqn.guanMingSys.entity.Notice
11 0
|
2月前
|
数据采集 JSON JavaScript
Python爬虫案例:抓取猫眼电影排行榜
python爬取猫眼电影排行榜数据分析,实战。(正则表达式,xpath,beautifulsoup)【2月更文挑战第11天】
70 2
Python爬虫案例:抓取猫眼电影排行榜
|
14天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
14天前
|
数据采集 JSON 网络协议
「Python系列」Python urllib库(操作网页URL对网页的内容进行抓取处理)
`urllib` 是 Python 的一个标准库,用于打开和读取 URLs。它提供了一组模块,允许你以编程方式从网络获取数据,如网页内容、文件等。
35 0
|
15天前
|
JavaScript
js 字符串String转对象Object
该代码示例展示了如何将一个以逗号分隔的字符串(`&#39;1.2,2,3,4,5&#39;`)转换为对象数组。通过使用`split(&#39;,&#39;)`分割字符串并`map(parseFloat)`处理每个元素,将字符串转换成浮点数数组,最终得到一个对象数组,其类型为`object`。
|
19天前
|
XML 编解码 数据格式
Python标准数据类型-String(字符串)
Python标准数据类型-String(字符串)
23 2
|
1月前
|
Python
如何使用Python的Requests库进行网络请求和抓取网页数据?
如何使用Python的Requests库进行网络请求和抓取网页数据?
13 0