栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python爬虫之BeatifulSoup

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python爬虫之BeatifulSoup

#安装
#pip install bs4

#1.拿到页面源代码
#2.使用bs4进行解析,拿到数据
import requests
from bs4 import BeautifulSoup
import csv
import re

url = "http://www.xinfadi.com.cn/getPriceData.html"
resp = requests.get(url)
resp.close()
# print(resp.text)

f = open("菜价.csv", mode="w",encoding='utf-8')
csvwriter = csv.writer(f)

#解析数据
#1.把页面源代码交给BeautifulSoup进行处理,生成bs对象
# page = BeautifulSoup(resp.text, "html.parser")#指定html解析器
obj1 = re.compile(r',"prodName":"(?P.*?)",.*?"prodCat":"(?P.*?)",.*?"lowPrice":"(?P.*?)",.*?'
                  r'"highPrice":"(?P.*?)",.*?"avgPrice":"(?P.*?)",', re.S)
result1 = obj1.finditer(resp.text)
for it in result1:

    dic = it.groupdict()
    csvwriter.writerow(dic.values())
f.close()
print("over!")
#2.从bs对象种查找数据
#find(标签,属性=值)
#find_all(标签,属性=值)
# table = page.find("table","class_="hq_table")  #加_因为class是python的关键字
# table = page.find("table",attrrs={"class": hq_table"})  #加_因为class是python的关键字
# print(page.text)
#拿到所有数据行
# trs = table.find_all("tr")[1:]
# for tr in trs:  #每一行
#     tds = tr.find_all("td")     #拿到每行中的所有td
#     name = tds[0].text      #.text表示拿到被标签所标记的内容
#     type = tds[1].text
#     max = tds[2].text
#     min = tds[3].text
#     avg = tds[4].text
#     csvwriter.writerow([name,type,max,min,avg])
#
# f.close()
# print("over!")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/866778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号