目标:抓取目标网站用正侧表达式并写入CSV里。
进度:基本达成目标,但还是有些小问题没有解决
存在的疑问:
- ide中调用执行文件不能显示完整
- 有些网站不能读取完
- 为什么会有换位符号,是因为js解析吗
还没解决的技术性问题:
- yield的具体用法
- CSV写入为什么没有头
- 更加深入的正侧表达式使用方法
- json写入
import json
import requests
from requests.exceptions import RequestException
import re
import time
import csv
def get_one_page(url):
response = requests.get(url)
response.encoding = 'utf-8'
if response.status_code == 200:
return response.text
return None
def main(offset):
url = 'https://www.newcger.com/aemoban/2496' + str(offset)+'.html'
html = get_one_page(url)
print(url)
print(html)
parse_one_page(html)
def parse_one_page(html):
pattern = re.compile('<title>(.*?)</title>.*?<meta name="keywords" content="(.*?)" />.*?center;"><img src="(.*?)".*?embed/(.*?)".*?<a href="https://pan.baidu.com/s/(.*?)".*?百度网盘 - 密码(.*?)</a>', re.S)
items = re.findall(pattern, html)
for item in items:
{
'name': item[0],
'tag': item[1],
'image': item[2],
'video': item[3],
'baidu': item[4],
'password': item[5],
}
print(items)
with open('data.csv', 'a', encoding='utf-8') as csvfile:
fieldnames = ['id', 'name', 'age','video']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'id':item[0], 'name':item[1], 'age': item[2],'video': item[3]})
if __name__ == '__main__':
for i in range(10):
main(offset=i + 1)
time.sleep(1)