在游覽器中xpath匹配成功,代碼中匹配缺為空的原因和解決


 

 一。代碼不同導致 

問題是這樣的,在游覽器中我們寫的xpath完美匹配到了我們想要的內容,可是在python代碼中運行的時候返回值缺為空

這代表我們的匹配規制實質上是失敗了的,但這是為什么呢?

於是我使用get請求,並打印我得到的html代碼,和網頁代碼比較后終於找到問題的原因

 

可以看到這里的class=“cover_data_china”屬性里面還多出來了一段noNewScroll,而這一段代碼在我們f12后的開發者工具中的代碼中是不一樣的

這就是為什么我們在游覽器中可以匹配而代碼中出錯的原因,因為html就不同,所以我們需要重新寫一邊xpath的匹配規則才能解決這個問題

二。不同游覽器的到的不同

我們知道,我們通常會帶上一個headers請求頭來說明我們的身份(是什么游覽器或者手機),實際上不同的游覽器得到的不一定是同一套網頁代碼,這時候,我們可以修改請求頭來解決

常見的User-Agent:的值


1) Chrome(谷歌)
Win7:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1
Win10:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
Chrome 17.0 – MAC
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11


2) Firefox(火狐)
Win7:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0
Firefox 4.0.1 – MAC
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1


3) Safari(Safari是蘋果計算機的操作系統Mac OS中的瀏覽器)
safari 5.1 – MAC
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50
safari 5.1 – Windows
Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50


4) Opera(歐朋瀏覽器可以在Windows、Mac和Linux三個操作系統平台上運行)
Opera 11.11 – MAC
User-Agent:Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11
Opera 11.11 – Windows
User-Agent:Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11


5) IE
IE 11
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
IE 9.0
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;
IE 8.0
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)
IE 7.0
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)
IE 6.0
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
WinXP+ie8:
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB7.0)
WinXP+ie7:
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)
WinXP+ie6:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)

6) 傲游
傲游(Maxthon)
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)


7) 搜狗
搜狗瀏覽器 1.x
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)


8) 360
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)

9) QQ瀏覽器
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)

https://blog.csdn.net/wangqing84411433/article/details/89600335


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM