【发布时间】:2019-06-15 07:31:51
【问题描述】:
我在 python 中创建了一个脚本,使用 pyppeteer 从网页中收集不同帖子的链接,然后通过进入解析每个帖子的标题他们的目标页面重用这些收集的链接。虽然内容是静态的,但我想知道 pyppeteer 在这种情况下是如何工作的。
我尝试将 main() 函数中的 browser 变量提供给 fetch() 和 browse_all_links() 函数,以便我可以一遍又一遍地重用同一个浏览器。
我目前的做法:
import asyncio
from pyppeteer import launch
url = "https://stackoverflow.com/questions/tagged/web-scraping"
async def fetch(page,url):
await page.goto(url)
linkstorage = []
await page.waitForSelector('.summary .question-hyperlink')
elements = await page.querySelectorAll('.summary .question-hyperlink')
for element in elements:
linkstorage.append(await page.evaluate('(element) => element.href', element))
return linkstorage
async def browse_all_links(page,link):
await page.goto(link)
await page.waitForSelector('h1 > a')
title = await page.querySelectorEval('h1 > a','(e => e.innerText)')
print(title)
async def main():
browser = await launch(headless=False,autoClose=False)
[page] = await browser.pages()
links = await fetch(page,url)
tasks = [await browse_all_links(page,url) for url in links]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
上述脚本获取了一些标题,但在执行过程中的某个时间点出现以下错误:
Possible to select <a> with specific text within the quotes?
Crawler Runs Too Slow
How do I loop a list of ticker to scrape balance sheet info?
How to retrive the url of searched video from youtbe using python
VBA-JSON to import data from all pages in one table
Is there an algorithm that detects semantic visual blocks in a webpage?
find_all only scrape the last value
#ERROR STARTS
Future exception was never retrieved
future: <Future finished exception=NetworkError('Protocol error (Runtime.releaseObject): Cannot find context with specified id')>
pyppeteer.errors.NetworkError: Protocol error (Runtime.releaseObject): Cannot find context with specified id
Future exception was never retrieved
【问题讨论】:
-
我看到你正在获取
href。这可能不完整url,即它可能是/contact而不是http://www.example.com/contact。在前面的案例中没有指定协议,因此我怀疑它会引发错误。 -
你错了@Vishnudev。当任何浏览器模拟器发挥作用时,大多数情况下检索到的 url 都是完整的,就像我在这个案例中看到的那样。
-
哦,好吧。我只是怀疑。如果链接工作正常,那么我不知道为什么会这样。
-
我从来没有听说过这个工具包,但我看到的第一个谷歌结果似乎很相关。以this 评论开头。
-
@robots.txt 为什么要使用asyncio 标签?已经存在 python-asyncio 标签,包含 2000 多个问题。
标签: python web-scraping puppeteer pyppeteer python-asyncio