【前提:菜鳥學習的記錄過程,如果有不足之處,還請各位大佬大神們指教(感謝)】
1.方法一:網站找到目標數據【單篇PDF】
https://bidding.sinopec.com/tpfront/xxgg/004005/
按F12,----檢查------network----
要看常規的請求方式---get---post
在請求表頭,看有沒有奇怪的值,可以會加密,
import requests# 一般帶上url,user——agent,headers,cookieheaders={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36','Cookie':'tpfront=4788ee85d9fd8926ef48c20bb8dc4c43; Hm_lvt_42e506478546400c16c57095f80950ed=1743408249; Hm_lpvt_42e506478546400c16c57095f80950ed=1743408249; HMACCOUNT=B0B7FD1EB0F629AE; BIGipServerPOOL_DZZBTB_234_80=3564697866.20480.0000; ASP.NET_SessionId=flwz1jfqof5hxmrdv0xizghj; TPFrame=13ac4d652fc425c52033851ae548024b'
}
# get里面放url
res=requests.get('https://bidding.sinopec.com/tpframe//AttachStorage202006/202412/J115/f8da7370-cbf6-499f-b0dc-83047805c8e4/%E4%B8%AD%E6%A0%87%E5%85%AC%E5%91%8A.pdf',headers=headers)
print(res)
print(res.text)
拿到的數據是亂碼,說明是二進制的數據,or 數據被加密了。
解決:把text換成 content
print(res.content)
就會得到一個二進制的數據,把這些數據放進一個二進制的文件保存
with open('石油test.pdf','wb')as f:f.wirte(response.content)
?2.方法二下載pdf
F12 找到html的中標公告.pdf?
類似url
```
"https://bidding.sinopec.com/tpframe//AttachStorage202006/202412/J115/ca1dce49-f03e-497a-a254-009ff09ee2bd/中標公告.pdf"
```
想要獲取這個url,就需要先獲取html代碼。
先去分析這個URL在html在哪個部分請求???
我們把想要的url復制,去查找
import requestsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36','Cookie': 'tpfront=4788ee85d9fd8926ef48c20bb8dc4c43; Hm_lvt_42e506478546400c16c57095f80950ed=1743408249; Hm_lpvt_42e506478546400c16c57095f80950ed=1743408249; HMACCOUNT=B0B7FD1EB0F629AE; BIGipServerPOOL_DZZBTB_234_80=3564697866.20480.0000; ASP.NET_SessionId=flwz1jfqof5hxmrdv0xizghj; TPFrame=13ac4d652fc425c52033851ae548024b'
}response=requests.get('https://bidding.sinopec.com/tpfront/infodetail/?infoid=ca1dce49-f03e-497a-a254-009ff09ee2bd&siteid=1&categoryNum=004005&RelateOuGuid=',headers=headers)
print(response.text)
上面,可以把頁面的html,下載。
在 HTML 和 CSS 中,ID 選擇器使用 #
符號,而 class 選擇器使用 .
(點)符號。
a[target="_blank"]table#filedown a
from bs4 import BeautifulSoupsoup=BeautifulSoup(response.text,'lxml')
print(soup.select('table#filedown a')[0])
```python
import requests
from bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
}
# 這個url指的是這個網頁的
response=requests.get('https://bidding.sinopec.com/tpfront/infodetail/?infoid=ca1dce49-f03e-497a-a254-009ff09ee2bd&siteid=1&categoryNum=004005&RelateOuGuid=',headers=headers)
# print(response.text)soup=BeautifulSoup(response.text,'lxml')
print(soup.select('table#filedown a')[0]['href'])pdf_url=soup.select('table#filedown a')[0]['href']# # 發送請求
res=requests.get(pdf_url,headers=headers)with open('石油2.pdf','wb')as f:f.write(res.content)print("成功啦")```