xicidaili.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from pyquery import PyQuery as pq
  2. from proxypool.schemas.proxy import Proxy
  3. from proxypool.crawlers.base import BaseCrawler
  4. from loguru import logger
  5. BASE_URL = 'https://www.xicidaili.com/'
  6. class XicidailiCrawler(BaseCrawler):
  7. """
  8. xididaili crawler, https://www.xicidaili.com/
  9. """
  10. urls = [BASE_URL]
  11. headers = {
  12. 'User-Agent': 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
  13. }
  14. @logger.catch
  15. def crawl(self):
  16. """
  17. crawl main method
  18. """
  19. for url in self.urls:
  20. logger.info(f'fetching {url}')
  21. html = self.fetch(url, headers=self.headers)
  22. for proxy in self.parse(html):
  23. logger.info(f'fetched proxy {proxy.string()} from {url}')
  24. yield proxy
  25. def parse(self, html):
  26. """
  27. parse html file to get proxies
  28. :return:
  29. """
  30. doc = pq(html)
  31. items = doc('#ip_list tr:contains(高匿)').items()
  32. for item in items:
  33. country = item.find('td.country').text()
  34. if not country or country.strip() != '高匿':
  35. continue
  36. host = item.find('td:nth-child(2)').text()
  37. port = int(item.find('td:nth-child(3)').text())
  38. yield Proxy(host=host, port=port)
  39. if __name__ == '__main__':
  40. crawler = XicidailiCrawler()
  41. for proxy in crawler.crawl():
  42. print(proxy)