小編給大家分享一下Python使用字典的案例,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
字典(Dictionary)在Python中是一種可變的容器模型,它是通過一組鍵(key)值(value)對組成,這種結構類型通常也被稱為映射,或者叫關聯數組,也有叫哈希表的。每個key-value之間用“:”隔開,每組用“,”分割,整個字典用“{}”括起來。
凡是用到鍵值對的地方,就可以用字典。爬蟲中的headers都可以用到字典
# coding:utf-8
import requests
from bs4 import BeautifulSoup
class SpiderProxy(object):
#Python版本為2.7以上
headers = {
"Host": "www.xicidaili.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Referer": "http://www.xicidaili.com/wt/1",
}
def __init__(self, session_url):
self.req = requests.session()
self.req.get(session_url)
def get_pagesource(self, url):
html = self.req.get(url, headers=self.headers)
return html.content
def get_all_proxy(self, url, n):
data = []
for i in range(1, n):
html = self.get_pagesource(url + str(i))
soup = BeautifulSoup(html, "lxml")
table = soup.find('table', id="ip_list")
for row in table.findAll("tr"):
cells = row.findAll("td")
tmp = []
for item in cells:
tmp.append(item.find(text=True))
data.append(tmp[1:3])
return data
session_url = 'http://www.xicidaili.com/wt/1'
url = 'http://www.xicidaili.com/wt/'
p = SpiderProxy(session_url)
proxy_ip = p.get_all_proxy(url, 10)
for item in proxy_ip:
if item:
print item看完了這篇文章,相信你對Python使用字典的案例有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。