search
HomeBackend DevelopmentPython TutorialPython crawler crawls American drama websites

Python crawler crawls American drama websites

Feb 27, 2017 am 10:24 AM
python crawler

I have always had the habit of watching American TV series. On the one hand, I can practice my English listening skills, and on the other hand, I can pass the time. It used to be possible to watch online on video websites, but since the restriction order imposed by the State Administration of Radio, Film and Television, it seems that imported American and British dramas are no longer updated simultaneously as before. However, as a nerd, how can I be willing to not follow any dramas, so I checked online and found an American drama download website [Tiantian American Dramas] that can be downloaded using Thunder. I can download various resources at will. Recently, I am obsessed with BBC’s High-definition documentary, nature is so beautiful.

Python crawler crawls American drama websites

Although I have found a resource website that can be downloaded, I have to open the browser every time, enter the URL, find the American drama, and then click the link to download. After a long time, the process becomes very cumbersome, and sometimes the website link cannot be opened, which is a bit troublesome. I happen to have been learning Python crawlers, so today I wrote a crawler on a whim to grab all the American drama links on the website and save them in a text document. If you want any drama, just open and copy the link to Xunlei to download it.

Python crawler crawls American drama websites

In fact, I originally planned to write something that finds a URL, uses requests to open it, grabs the download link, and crawls the entire site starting from the homepage. However, there are a lot of repeated links, and the URL of the website is not as regular as I thought. After writing for a long time, I still haven't written the kind of divergent crawler I want. Maybe I am not mature enough, so keep working hard. . .

Later I discovered that the links to the TV series were all in the article, and there was a number behind the article URL, like this http://cn163.net/archives/24016/, so I was smart and used Based on the crawler experience I wrote before, the solution is to automatically generate the URL. Can’t the number behind it be changed? Moreover, each drama is unique, so I tried to find out how many articles there are, and then use the range function to directly Continuously generate numbers to construct the url.

But many URLs do not exist, so they will hang up directly. Don’t worry, we are using requests, and its built-in status_code is used to determine the status returned by the request, so as long as it is the returned status We skip all those with code 404, and crawl the other links, which solves the URL problem.

The following is the implementation code of the above steps.

def get_urls(self):
  try:
    for i in range(2015,25000):
      base_url='http://cn163.net/archives/'
      url=base_url+str(i)+'/'
      if requests.get(url).status_code == 404:
        continue
      else:
        self.save_links(url)
  except Exception,e:
    pass

The rest went very smoothly. I found a similar crawler written by someone before on the Internet, but it only crawled one article, so I learned from it. Take a look at its regular expression. I used BeautifulSoup but the effect was not as good as the regular method, so I gave up decisively. There is no limit to my learning. However, the effect is not so ideal. About half of the links cannot be crawled correctly and need to continue to be optimized.

# -*- coding:utf-8 -*-
import requests 
import re
import sys
import threading
import time
reload(sys)
sys.setdefaultencoding('utf-8')
class Archives(object):

  def save_links(self,url):
    try:

      data=requests.get(url,timeout=3)
      content=data.text
      link_pat='"(ed2k://\|file\|[^"]+?\.(S\d+)(E\d+)[^"]+?1024X\d{3}[^"]+?)"'
      name_pat=re.compile(r'<h2 id="">(.*?)</h2>',re.S)
      links = set(re.findall(link_pat,content))
      name=re.findall(name_pat,content)
      links_dict = {}
      count=len(links)
    except Exception,e:
      pass
    for i in links:
      links_dict[int(i[1][1:3]) * 100 + int(i[2][1:3])] = i#把剧集按s和e提取编号
    try:
      with open(name[0].replace('/',' ')+'.txt','w') as f:
        print name[0]
        for i in sorted(list(links_dict.keys())):#按季数+集数排序顺序写入
          f.write(links_dict[i][0] + '\n')
      print "Get links ... ", name[0], count
    except Exception,e:
      pass

  def get_urls(self):
    try:
      for i in range(2015,25000):
        base_url='http://cn163.net/archives/'
        url=base_url+str(i)+'/'
        if requests.get(url).status_code == 404:
          continue
        else:
          self.save_links(url)
    except Exception,e:
      pass
  def main(self):
    thread1=threading.Thread(target=self.get_urls())
    thread1.start()
    thread1.join()
  if __name__ == '__main__':
  start=time.time()
  a=Archives()
  a.main()
  end=time.time()
  print end-start

The complete version of the code also uses multi-threading, but it feels useless. It seems to be more than 20,000 parts because of Python's GIL. I thought it would take a long time to complete the crawling, but excluding the URL errors and unmatched URLs, the total crawling time was less than 20 minutes. I originally wanted to use Redis to crawl on two Linux machines, but after a lot of fussing, I felt it was unnecessary, so I left it at that and will do it later when I need more data.

Another problem that tortured me during the process was the saving of file names. I must complain here. File names in txt text format can have spaces, but they cannot have slashes, backslashes, brackets etc. This is the problem. I spent the whole morning on this. At first I thought it was an error in crawling the data. After checking for a long time, I found out that the crawled drama title had a slash in it. This made me miserable. .

For more articles related to Python crawlers crawling American drama websites, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.