使用python爬取資料實測記錄

2021-08-20 08:23:23 字數 1531 閱讀 5987

1、爬取網頁url資料返回301、302報錯

class modianspider(scrapy.spider):

name = 'modian'

allowed_domains = ['modian.com']

start_urls = ['']

def parse(self, response):

hrefs = response.xpath('//div[@class="myproject clearfix"]/ul/li/a/@href').extract()

for href in hrefs:

yield scrapy.request(href, meta=, callback=self.parse_pro_page)

def parse_pro_page(self, response):

item = modianitem()

item['id'] = response.xpath('//div/@data-pro_id').extract()

item['title'] = response.xpath('//h3[@class="title"]/span/text()').extract()

item['href'] = response.meta['href']

測試列印url,301/302報錯部分提示get位址由變成

排查發現,settings中寫的user_agent_list(用於隨機user-agent)中加入了手機**,導致抓取出的url形式變化。修改之後測試列印url和title均正常無報錯。

2、爬取js動態資料

部分資料在瀏覽器「審查元素」中可以找到,「檢視源**」中無法獲取,查詢後了解這是動態資料。

檢視動態資料方法:開啟瀏覽器右鍵「審查元素」,切換到network,選中hxr。重新整理頁面後,hxr中獲取新鏈結。最終在某個鏈結的preview/response裡找到目標資料——摩點某專案的集資金額。

找到目標資料後開始想辦法抓取。

多開幾個專案比對一下,觀察url樣式大致是:

數字_數字&ids=數字&if_all=1&_=數字

其中,ids=數字,這裡的數字值正好是之前抓到的專案id。嘗試使用正規表示式抓取這個url。這裡網上有說應該用python傳送get還是post請求,沒看懂,看到request method是get,就用了requests.get

get_data = 

return_data = requests.get("", params=get_data)

print(return_data.text)

列印結果確實把response內的所有內容(包含目標資料)爬取到了,接下來要從中繼續提取目標資料了。

python爬取電影和美食資料實戰

本文使用的是requests 正則來匹配網頁內容,對於資料量較多的採用了多執行緒抓取的方法,共3個案例,分別是抓取貓眼電影top100榜單和淘票票正在熱映的電影資訊 以及美團的美食資料。這幾個案例採用的方法大同小異。1 首先選擇想要爬取的 2 確定要用的模組,requests,json,re三個模組...

python爬取網頁資料例項 一

coding utf 8 from lxml import etree import urllib2 import random import urlparse 設定網路 proxy info proxy support urllib2.proxyhandler openner urllib2.bu...

如何使用python爬取資料

在爬取資料之前首先使用 pip install requests 命令 import requests base url 此處為你所要爬取資料的 header 此處為偽裝成瀏覽器 res requests.get base url,headers header 傳送請求並返回包含相應的html檔案內...