python爬取阳光电影保存mysql

import requests
from lxml import etree
import re
import pymysql
# 定义url


headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}

# 连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='python', charset='utf8')
# 创建光标
cursor = db.cursor()
# 获取三次分页
for p in range(3):
    url = 'http://www.ygdy8.com/html/gndy/dyzz/list_23_{}.html'
    # 循环一次 页码加一
    # print(p)
    p+=1
    url = url.format(p)
    print(url)
    # 发送请求
    req = requests.get(url,headers=headers)
    # 强制定义编码
    req.encoding ='gb2312'
    # 格式化数据
    response = req.text
    # print(response)
    # with open('dianying.html','wb' ) as f:
    #     f.write(req.content)
    # 获取网页的obj
    html_obj = etree.HTML(response)
    # 定位数据
    html_list = html_obj.xpath('//div[@class="co_content8"]/ul/td/table/tr[2]/td[2]/b/a/@href')
    # print(html_list)
    # 循环列表 拿出每条数据
    for i in html_list:
        # print(i)
        # 拼接url
        url_b = 'http://www.ygdy8.com{}'.format(i)
        # print(url)
        # 发送请求
        req = requests.get(url_b, headers=headers)
        # with open('dianying.html', 'wb') as f:
        #     f.write(response.content)
        # 定义编码
        req.encoding = 'gb2312'
        # 转换格式
        response = req.text
        # 正则匹配
        href =re.search(r'href="(.*)"><strong><font', response).group(1)
        title =re.search(r'<font color=#07519a>(.*)</font></h1></div>', response).group(1)
        # print(href)
        print(title)
        sql = '''insert into dianying values (null,'{}','{}')'''.format(title,href)
        cursor.execute(sql)
        db.commit()

cursor.close()
db.close()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值