其他分享
首页 > 其他分享> > 正则表达式爬虫遇到的问题

正则表达式爬虫遇到的问题

作者:互联网

正则爬虫小例子

import re
import requests

# url = "http://www.redbull.com.cn/about/branch"
# 上面为网站
# page = requests.get(url).text
# 上面为把网站的数据提出来
with open('a.txt', 'r', encoding='utf8') as f:
    res = f.read()
# 上面为文件形式
# a = re.compile('<h2>(.*)</h2><p class=\'mapIco\'>(.*)</p><p class=\'mailIco\'>(.*)</p><p class=\'telIco\'>(.*)</p></li>')
# 一定要把双引号转义!!!!!不然取不到数据
a = re.compile('<h2>(.*?)</h2><p class=\'mapIco\'>(.*?)</p><p class=\'mailIco\'>(.*?)</p><p class=\'telIco\'>(.*?)</p>')

# z = re.compile()

# data = re.findall(a, page)

data = re.findall(a, res)
print(data)
with open('b.txt','a',encoding='utf8') as f:
    for i in data:
        f.write(f'''
            公司名称: {i[0]}
            公司地址: {i[1]}
            邮件信息: {i[2]}
            电话: {i[3]}
              ''')

标签:遇到,正则表达式,open,encoding,爬虫,compile,re,txt,data
来源: https://www.cnblogs.com/zhengkaijian/p/16069930.html