python爬取網頁

1. 使用requests庫

import requests 
url="http://www.starbaby.cn/zhinan/609987" 
req =requests.get(url) 
req.encoding='utf-8' #顯式地指定網頁編碼,一般情況可以不用 
print(req.text)

2. 使用BeautifulSoup

from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import requests

def run():
    r = requests.get('http://zy.upln.cn/gongshi2014/index.html')
    soup = r.text.encode(r.encoding) #這裏獲取的text先按照指定的字符集解析下,這樣gbk、utf8都可以了
    soup = BeautifulSoup(soup, 'html.parser')
    soup = soup.find('tbody')
    for x in soup.find_all('tr'):
        for y in x.find_all('td'):
            s = y.a.text
            print(s)


if __name__=="__main__":
    run()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章