小白一枚,學習python爬蟲中······純當學習筆記了,大神勿噴。
今天,帶來的是58同城單頁商品數(shù)據(jù)爬取。

要用到的:
pycharm
chrome瀏覽器
python庫:requests,Beautifulsoup4
任務分析:
1.解析當前頁面
?。?獲取當前頁面里每個商品的鏈接
?。?剔除推廣和轉轉商品
4.解析商品的鏈接,獲取商品標題,價格,發(fā)布時間,區(qū)域的信息
一、解析當前頁面
導入所需要的庫文件

定義當前網(wǎng)址,提前創(chuàng)建一個空的列表用來放商品鏈接

定義一個函數(shù)用來獲取商品鏈接

用requests的get方法發(fā)起網(wǎng)頁請求

解析網(wǎng)頁

右鍵檢查商品列表


確定定位位置

用for循環(huán)和if條件判斷結合剔除轉轉商品和推廣商品,把剩余商品的鏈接(即獲取的結果里的href里的內(nèi)容)添加到列表real_url_list中

二、獲取商品信息
定義獲取商品信息的函數(shù)

調(diào)用獲取商品鏈接的函數(shù)

用for循環(huán)遍歷每一個商品鏈接,把商品信息裝進data字典里并打印data

三、調(diào)用函數(shù)獲取結果

完整代碼如下:
import requests
from bs4 import BeautifulSoup
url='http://bj.58.com/pbdn/0/'
real_url_list=[]
def get_link():
wb_data=requests.get(url)
soup=BeautifulSoup(wb_data.text,'lxml')
real_url=soup.select('td.t a.t')
for i in real_url:
if str('jump')in str(i) or str('zhuanzhuan')in str(i):
pass
else:
real_url_list.append(i.get('href'))
return real_url_list
def get_item_info():
get_link()
for i in real_url_list:
wb_data=requests.get(i)
soup=BeautifulSoup(wb_data.text,'lxml')
data={
'title':soup.title.text,
'price':soup.select(' span.price')[0].text,
'time':soup.select('li.time')[0].text if soup.find_all('li','time')else None,
'area':list(soup.select( 'span.c_25d')[0].stripped_strings )if soup.find_all('span','c_25d')else None,
}
print(data)
get_item_info()
運行結果如下:

注意:
python對于縮進有著嚴格的要求,因為簡書的markdown不太會用,所附代碼的縮進并非是python默認的格式,但是對齊是正確的,若要復制代碼運行參考對齊格式就好。
下期預告:
老司機帶你飛,把煎蛋網(wǎng)的妹子圖帶回家
