BeautifulSoup 抓取資料

2022-06-23 10:21:07 字數 2826 閱讀 1214

抓取天氣

import

requests

from bs4

import

beautifulsoup

# from pyecharts

import

barcities_temp =

# 處理抓取頁面

def parse_url(url):

resp = requests.get(url, headers=headers)

text = resp.content.decode("utf-8")

soup = beautifulsoup(text, "lxml")

conmidtab = soup.find("div", attrs=)

tables = conmidtab.find_all("table")

fortable in tables:

trs = table.find_all("tr")[2:]

forindex, tr in enumerate(trs):

cities ={}

tds = tr.find_all("td")

city_td = tds[0]

if index == 0:

city_td = tds[1]

city = list(city_td.stripped_strings)[0]

temp_td = tds[-2]

min_temp = list(temp_td.stripped_strings)[0]

cities["城市"] =city

cities["最低溫度"] =str(min_temp)

def main():

urls =[

'','',

'','',

'','',

'','']

forurl in urls:

parse_url(url)

# 分析資料排序

cities_temp.sort(key=lambda data: data['最低溫度'])

data = cities_temp[0:10]

ford in data:

fork, v in d.items():

print(k + ": " +str(v))

print("*" * 30)

if __name__ == '__main__':

main()

抓取京東的資料

import

requests

from bs4

import

beautifulsoup

class

spiders:

def __init__(self, page):

self.url = ''.format(page)

self.headers =

self.search_urls = ''self.pids =set() # 頁面中所有的id,用來拼接剩下的30張的url,使用集合可以有效的去重

self.img_urls =set() # 得到的所有的url

# 得到每一頁的網頁原始碼

def get_html(self):

res = requests.get(self.url, headers=self.headers)

html =res.text

return

html

# 得到每乙個頁面的id

def get_pids(self):

html =self.get_html()

soup = beautifulsoup(html, 'lxml')

lis = soup.find_all("li", class_='gl-item')

forli in lis:

data_pid = li.get("data-sku")

if(data_pid):

self.pids.add(data_pid)

# 得到每乙個頁面的和一些資料,由於這是aiax載入的,因此前面一段的img屬性是src,後面的屬性是data-lazy-img

def get_src_imgs_data(self):

html =self.get_html()

soup = beautifulsoup(html, 'lxml')

divs = soup.find_all("div", class_='p-img') #

fordiv in divs:

img_1 = div.find("img").get('data-lazy-img') # 得到沒有載入出來的url

img_2 = div.find("img").get("src") # 得到已經載入出來的url

page = i * 2 - 1 # 這裡每一頁對應的都是奇數,但是ajax的請求都是偶數的,所有在獲取擴充套件的網頁時都要用page+1轉換成偶數

spiders(page).main()

BeautifulSoup常用方法

1.初始化 2.查詢指定標籤 eg 要找到符合的所有標籤 p.findall div 反覆利用標籤特徵可以找到最終需要的標籤 3.直接加標籤名可以找到所有子標籤 eg 找到所有標籤 p.td 4.直接以字典形式,可以訪問標籤內對應屬性的值 eg 要找到 中href 的值 www.csdn.net p...

BeautifulSoup學習筆記

prettify 將html 格式化 get text 獲得所有文字內容 contens 返回所有子節點 children 返回子節點生成器 descendants 返回所有子孫節點的生成器 strings 返回包含的多個字串的生成器 stripped strings 返回包含的多個字串 去除多餘空...

爬蟲 BeautifulSoup 模組

二 根據這個dom樹就可以按照節點的名稱 屬性和文字搜尋節點 find all 方法會搜尋出所有滿足要求的節點,find 方法只會搜尋出第乙個滿足要求的節點 兩個方法的引數一模一樣 三 得到節點以後,就可以訪問它的名稱 屬性 文字。a為標籤名稱 超連結 href,class為屬性,顯示在頁面上的是p...