1. 程式人生 > >爬取西刺ip的插入資料庫相關問題

爬取西刺ip的插入資料庫相關問題

今晚解決了前幾天爬取西刺ip網不能插入資料庫的問題,成功爬取並插入資料庫的程式碼如下

# encoding: utf-8
import re
import requests
from scrapy.selector import Selector
import MySQLdb

conn = MySQLdb.connect(
    host="localhost",
    #port=3306,
    user="root",
    passwd="1234",
    db="jobbole",
    charset="utf8")
cursor = conn.cursor()


def crawl_ips():
    # 爬取西刺的免費ip代理
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"}
    for i in range(1568):
        res = requests.get(
            "http://www.xicidaili.com/nn/{0}".format(i),
            headers=headers)

        selector = Selector(text=res.text)
        all_trs = selector.css("#ip_list tr")

        ip_list = []
        for tr in all_trs[1:]:
            speed_str = tr.css(".bar::attr(title)").extract()[0]
            if speed_str:
                speed = float(speed_str.split("秒")[0])
            all_texts = tr.css("td::text").extract()
            match_obj1 = re.match(".*'HTTPS'.*", str(all_texts))
            match_obj2 = re.match(".*'HTTP'.*", str(all_texts))
            proxy_type = ""
            if match_obj1:
                proxy_type = "HTTPS"
            elif match_obj2:
                proxy_type = "HTTP"
            ip = all_texts[0]
            port = all_texts[1]

            ip_list.append((ip, port, proxy_type, speed))

        for ip_info in ip_list:
            cursor.execute(
                "insert xici(ip, port, speed, proxy_type) VALUES('{0}', '{1}', {2}, '{3}')".format(
                    ip_info[0], ip_info[1], ip_info[3], ip_info[2]))
            conn.commit()
print(crawl_ips())

但是又出現了新的問題。就是一個ip地址可以對應多個埠。但是之前我設定的是ip為主鍵,這當出現兩個相同的ip時,爬蟲就會停止,如下圖所示。

解決這個問題的辦法就是進行雙主鍵,ip和port都成為主鍵,只要兩個不同時相同就算新的可用ip,插入資料庫中。

暫時還不會。