Python爬蟲必備技巧詳細總結

自定義函數

import requests
from bs4 import BeautifulSoup
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0'}
def baidu(company):
    url = 'https://www.baidu.com/s?rtt=4&tn=news&word=' + company
    print(url)
    html = requests.get(url, headers=headers).text
    s = BeautifulSoup(html, 'html.parser')
    title=s.select('.news-title_1YtI1 a')
    for i in title:
        print(i.text)
# 批量調用函數
companies = ['騰訊', '阿裡巴巴', '百度集團']
for i in companies:
    baidu(i)

批量輸出多個搜索結果的標題

image-20211021110056346

結果保存為文本文件

import requests
from bs4 import BeautifulSoup
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0'}
def baidu(company):
    url = 'https://www.baidu.com/s?rtt=4&tn=news&word=' + company
    print(url)
    html = requests.get(url, headers=headers).text
    s = BeautifulSoup(html, 'html.parser')
    title=s.select('.news-title_1YtI1 a')
    fl=open('test.text','a', encoding='utf-8')
    for i in title:
        fl.write(i.text + '\n')
# 批量調用函數
companies = ['騰訊', '阿裡巴巴', '百度集團']
for i in companies:
    baidu(i)

image-20211021111507772

寫入代碼

fl=open('test.text','a', encoding='utf-8')
for i in title:
	fl.write(i.text + '\n')

異常處理

for i in companies:
    try:
        baidu(i)
        print('運行成功')
    except:
        print('運行失敗')

寫在循環中 不會讓程序停止運行 而會輸出運行失敗

休眠時間

import time
for i in companies:
    try:
        baidu(i)
        print('運行成功')
    except:
        print('運行失敗')
time.sleep(5)

time.sleep(5)

括號裡的單位是秒

放在什麼位置 則在什麼位置休眠(暫停)

爬取多頁內容

百度搜索騰訊

image-20211021115808442

切換到第二頁

image-20211021115857316

去掉多多餘的

https://www.baidu.com/s?wd=騰訊&pn=10

分析出

https://www.baidu.com/s?wd=騰訊&pn=0 為第一頁
https://www.baidu.com/s?wd=騰訊&pn=10 為第二頁
https://www.baidu.com/s?wd=騰訊&pn=20 為第三頁
https://www.baidu.com/s?wd=騰訊&pn=30 為第四頁
……….

代碼

from bs4 import BeautifulSoup
import time
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0'}
def baidu(c):
    url = 'https://www.baidu.com/s?wd=騰訊&pn=' + str(c)+'0'
    print(url)
    html = requests.get(url, headers=headers).text
    s = BeautifulSoup(html, 'html.parser')
    title=s.select('.t a')
    for i in title:
        print(i.text)

for i in range(10):
    baidu(i)
    time.sleep(2)

image-20211021130805642

到此這篇關於Python爬蟲必備技巧詳細總結的文章就介紹到這瞭,更多相關Python 爬蟲技巧內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: