Home Backend Development Python Tutorial Python crawler obtains websites of American dramas

Python crawler obtains websites of American dramas

Mar 18, 2017 am 11:46 AM
python

This article was originally created by MaNong.com – Xiao Hao. Please read the reprint requirements at the end of the article for reprinting. Welcome to participate in our paid contribution plan!

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.

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 crawler, 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 it and copy the link to You can download it via Thunder.

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 cleverly used the crawler experience I wrote before. The solution is to automatically generate the URL. Can’t the number behind it be changed? And each drama is unique, so I tried to find out how many articles there are. , and then use the range function to directly generate numbers continuously 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
Copy after login

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 borrowed its regular expressions. 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&#39;<h2 class="entry_title">(.*?)</h2>&#39;,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(&#39;/&#39;,&#39; &#39;)+&#39;.txt&#39;,&#39;w&#39;) as f:
                print name[0]
                for i in sorted(list(links_dict.keys())):#按季数+集数排序顺序写入
                    f.write(links_dict[i][0] + &#39;\n&#39;)
            print "Get links ... ", name[0], count
        except Exception,e:
            pass

    def get_urls(self):
        try:
            for i in range(2015,25000):
                base_url=&#39;http://cn163.net/archives/&#39;
                url=base_url+str(i)+&#39;/&#39;
                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__ == &#39;__main__&#39;:
    start=time.time()
    a=Archives()
    a.main()
    end=time.time()
    print end-start
Copy after login

The full version of the code also uses multi-threading, but it seems useless. It may be because of Python's GIL. There seem to be more than 20,000 dramas. I thought it would take a long time to complete the crawling. , but excluding URL errors and unmatched URLs, the total crawling time is 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. .

The above is the detailed content of Python crawler obtains websites of American dramas. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles