python - 如何使用 "requests"模块 python 进行简单的快速请求?

标签 python performance beautifulsoup python-requests

我是 python 的初学者,我只是想用模块 requestsBeautifulSoup 抓取 web Website我提出要求。

和我的简单代码:

import requests, time, re, json
from bs4 import BeautifulSoup as BS

url = "https://www.jobstreet.co.id/en/job-search/job-vacancy.php?ojs=6"

def list_jobs():
    try:
        with requests.session() as s:
            st = time.time()
            s.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0'}
            req = s.get(url)
            soup = BS(req.text,'html.parser')
            attr = soup.findAll('div',class_='position-title header-text')
            pttr = r".?(.*)Rank=\d+"
            lists = {"status":200,"result":[]}
            for a in attr:
                sr = re.search(pttr, a.find("a")["href"])
                if sr:
                    title = a.find('a')['title'].replace("Lihat detil lowongan -","").replace("\r","").replace("\n","")
                    url = a.find('a')['href']
                    lists["result"].append({
                        "title":title,
                        "url":url,
                        "detail":detail_jobs(url)
                    })
            print(json.dumps(lists, indent=4))
            end = time.time() - st
            print(f"\n{end} second")
    except:
        pass

def detail_jobs(find_url):
    try:
        with requests.session() as s:
            s.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0'}
            req = s.get(find_url)
            soup = BS(req.text,'html.parser')
            position = soup.find('h1',class_='job-position').text
            name = soup.find('div',class_='company_name').text.strip("\t")
            try:
                addrs = soup.find('div',class_='map-col-wraper').find('p',{'id':'address'}).text
            except Exception:
                addrs = "Unknown"
            try:
                loct = soup.find('span',{'id':'single_work_location'}).text
            except Exception:
                loct = soup.find('span',{'id':'multiple_work_location_list'}).find('span',{'class':'show'}).text        
            dests = soup.findAll('div',attrs={'id':'job_description'})
            for select in dests:
                txt = select.text if not select.text.startswith("\n") or not select.text.endswith("\n") else select.text.replace("\n","")
                result = {
                    "name":name,
                    "location":loct,
                    "position":position,
                    "description":txt,
                    "address":addrs
                }
                return result
    except:
        pass

它们都运行良好,但需要很长时间才能显示结果,时间总是在 13/17 秒以上

我不知道如何提高我的请求速度

我试过在 stack 和 google 上搜索,他们说使用 asyncio,但对我来说太难了。

如果有人有简单的技巧如何通过简单的操作来提高速度,我将非常感激..

抱歉我的英语不好

最佳答案

通过网络抓取等项目学习 Python 非常棒。这就是我接触 Python 的方式。也就是说,要提高抓取速度,您可以做三件事:

  1. 将 html 解析器更改为更快的东西。 'html.parser' 是其中最慢的。尝试更改为“lxml”或“html5lib”。 (阅读https://www.crummy.com/software/BeautifulSoup/bs4/doc/)

enter image description here

  1. 放弃循环和正则表达式,因为它们会减慢您的脚本。只需使用 BeautifulSoup 工具、文本和 strip ,然后找到正确的标签。(请参阅下面我的脚本)

  2. 由于网络抓取的瓶颈通常是 IO,等待从网页获取数据,使用异步或多线程将提高速度。在下面的脚本中,我使用了多线程。目的是同时从多个页面拉取数据。

因此,如果我们知道最大页面数,我们可以将我们的请求分块到不同的范围内并分批提取它们:)

代码示例:

from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime

import requests
from bs4 import BeautifulSoup as bs

data = defaultdict(list)

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0'}

def get_data(data, headers, page=1):

    # Get start time
    start_time = datetime.now()
    url = f'https://www.jobstreet.co.id/en/job-search/job-vacancy/{page}/?src=20&srcr=2000&ojs=6'
    r = requests.get(url, headers=headers)

    # If the requests is fine, proceed
    if r.ok:
        jobs = bs(r.content,'lxml').find('div',{'id':'job_listing_panel'})
        data['title'].extend([i.text.strip() for i in jobs.find_all('div',{'class':'position-title header-text'})])
        data['company'].extend([i.text.strip() for i in jobs.find_all('h3',{'class':'company-name'})])
        data['location'].extend([i['title'] for i in jobs.find_all('li',{'class':'job-location'})] )
        data['desc'].extend([i.text.strip() for i in jobs.find_all('ul',{'class':'list-unstyled hidden-xs '})])
    else:
        print('connection issues')
    print(f'Page: {page} | Time taken {datetime.now()-start_time}')
    return data
    

def multi_get_data(data,headers,start_page=1,end_page=20,workers=20):
    start_time = datetime.now()
    # Execute our get_data in multiple threads each having a different page number
    with ThreadPoolExecutor(max_workers=workers) as executor:
        [executor.submit(get_data, data=data,headers=headers,page=i) for i in range(start_page,end_page+1)]
    
    print(f'Page {start_page}-{end_page} | Time take {datetime.now() -     start_time}')
    return data


# Test page 10-15
k = multi_get_data(data,headers,start_page=10,end_page=15)

结果: enter image description here

解释 multi_get_data 函数:

此函数将在不同的线程中调用 get_data 函数并传递所需的参数。目前,每个线程都有不同的页码来调用。 worker 的最大数量设置为 20,即 20 个线程。您可以相应地增加或减少。

我们已经创建了变量数据,一个默认的字典,它接受列表。所有线程都将填充这个数据。然后可以将该变量转换为 json 或 Pandas DataFrame :)

如您所见,我们有 5 个请求,每个请求用时不到 2 秒,但总用时仍不到 2 秒;)

享受网络抓取。

更新_:22/12/2019

我们还可以通过使用具有单个 header 更新的 session 来提高速度。所以我们不必在每次通话时都开始 session 。

from requests import Session

s = Session()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\
                         'AppleWebKit/537.36 (KHTML, like Gecko) '\
                         'Chrome/75.0.3770.80 Safari/537.36'}
# Add headers
s.headers.update(headers)

# we can use s as we do requests
# s.get(...)
...

关于python - 如何使用 "requests"模块 python 进行简单的快速请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54157946/

相关文章:

python - 将不带分隔符的单个 json 对象转换为可立即处理的有效 json 文件

python - python中类的副本

python - 如何使用 Crontab 在 Django 环境中运行 Python 文件?

c# - 减少到服务器/数据库的往返

performance - 为什么有很多用户生成的表不是一个好主意

mysql - 如果某些列是可选的,用覆盖索引查询一堆列的最佳方法是什么?

python - 如何将外部标签添加到 BeautifulSoup 对象

Python:生成所有成对唯一配对

javascript - 抓取需要您向下滚动的网站

python - 在Python BeautifulSoup中如何移动标签