爬虫入门学习总结(1)——使用正侧表达式并写入CSV

目标:抓取目标网站用正侧表达式并写入CSV里。

进度:基本达成目标,但还是有些小问题没有解决

存在的疑问:

  1. ide中调用执行文件不能显示完整
  2. 有些网站不能读取完
  3. 为什么会有换位符号,是因为js解析吗

还没解决的技术性问题:

  1. yield的具体用法
  2. CSV写入为什么没有头
  3. 更加深入的正侧表达式使用方法
  4. 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) 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值