什么是最好的方式来刮这个网站?(非硒)

2024-10-01 00:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在开始之前,TLDR位于底部

因此,我正试图根据用户输入的搜索结果,从https://rarbgmirror.com/中搜寻torrent magnet链接及其torrent标题名称。我已经通过以下代码了解了如何使用BeautifulSoup和请求来实现这一点:

from bs4 import BeautifulSoup
import requests
import re

query = input("Input a search: ")
link = 'https://rarbgmirror.com/torrents.php?search=' + query

magnets = []
titles = []
try:
    request = requests.get(link)
except:
    print("ERROR")
source = request.text
soup = BeautifulSoup(source, 'lxml')
for page_link in soup.findAll('a', attrs={'href': re.compile("^/torrent/")}):
    page_link = 'https://www.1377x.to/' + page_link.get('href')
    try:
        page_request = requests.get(page_link)
    except:
        print("ERROR")

    page_source = page_request.content
    page_soup = BeautifulSoup(page_source, 'lxml')
    link = page_soup.find('a', attrs={'href': re.compile("^magnet")})
    magnets.append(link.get('href'))
    title = page_soup.find('h1')
    titles.append(title)

print(titles)
print(magnets)

我几乎可以肯定,这段代码中没有错误,因为代码最初是为https://1377x.to编写的,目的相同,如果您查看这两个网站的HTML结构,它们对磁铁链接和标题名称使用相同的标记。但是如果代码有错误,请向我指出

经过一些研究,我发现问题在于https://rarbgmirror.com/使用JavaScript动态加载网页。因此,经过更多的研究,我发现硒被推荐用于此目的。使用selenium一段时间后,我发现使用它有一些缺点,例如:

  • 刮削的缓慢速度
  • 运行应用程序的系统必须安装selenium浏览器(我计划使用pyinstaller打包应用程序,这将是一个问题)

因此,我请求一种替代selenium的方法来抓取动态加载的网页

TLDR: 我想要一个替代selenium的方法来抓取一个使用JavaScript动态加载的网站

PS:GitHub回购协议 https://github.com/eliasbenb/MagnetMagnet


Tags: 代码httpscomsourcegetrequestseleniumpage
2条回答

工作解决方案 寻求答案的人免责声明:此方法不适用于RARBG以外的任何网站

我把同样的问题贴到reddit的r/learnpython上,那里有人找到了一个很好的答案,满足了我的所有要求。您可以找到原始注释here

他发现rarbg是从here获得信息的

您可以通过更改链接中的“查询”来更改搜索者。在那个页面上有每个torrent的所有信息,所以使用请求和bs4我收集了所有信息

以下是工作代码:

query = input("Input a search: ")
rarbg_link = 'https://torrentapi.org/pubapi_v2.php?mode=search&search_string=' + query + '&token=lnjzy73ucv&format=json_extended&app_id=lol'
try:
    request = requests.get(rarbg_link, headers={'User-Agent': 'Mozilla/5.0'})
except:
    print("ERROR")
source = request.text
soup = str(BeautifulSoup(source, 'lxml'))
soup = soup.replace('<html><body><p>{"torrent_results":[', '')
soup = soup.split(',')
titles = str([i for i in soup if i.startswith('{"title":')])
titles = titles.replace('{"title":"', '')
titles = titles.replace('"', '')
titles = titles.split("', '")
for title in titles:
    title.append(titles)
    links = str([i for i in soup if i.startswith('"download":')])
    links = links.replace('"download":"', '')
    links = links.replace('"', '')
    links = links.split("', '")
    for link in links:
        magnets.append(link)

如果你只使用Chrome,你可以通过谷歌查看Puppeteer。它速度快,并且与Chrome开发工具集成得很好

相关问题 更多 >