其他分享
首页 > 其他分享> > 【爬虫】bs4

【爬虫】bs4

作者:互联网

# -*- coding:utf-8 -*-
# 1、拿到页面源代码
# 2、使用bs4解析,拿到数据

import requests
from bs4 import BeautifulSoup
import csv

url = "http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml"
resp = requests.get(url)

f = open("/python/hyr/reptile/download/菜价.csv", mode="w")
csvwriter = csv.writer(f)

# 解析数据
# 1、把页面源代码交给BeautifulSoup进行处理,生产bs对象
page = BeautifulSoup(resp.text, "html.parser")  # 制定html解析器
# 2、从bs对象中查找数据,find(标签,属性=值),findall(标签,属性=值)
# table = page.find("table", class_="hq_table")  # class是Python的关键字,所以要加上_
table = page.find("table", attrs={"class": "hq_table"})  # 换成字典

# 拿到所有行
trs = table.find_all("tr")[1:]  # 做切片
for tr in trs:  # 每一行
    tds = tr.find_all("td")  # 拿到每行中的所有td
    name = tds[0].next  # 拿到标签的内容
    name1 = tds[1].next
    name2 = tds[2].next
    name3 = tds[3].next
    name4 = tds[4].next
    name5 = tds[5].next
    csvwriter.writerow([name, name1, name2, name3, name4, name5])

f.close()
print("over")

 

标签:bs4,tr,爬虫,next,BeautifulSoup,tds,table,find
来源: https://www.cnblogs.com/hanyr/p/16368545.html