我已经在python
和pyppeteer
的结合下编写了一个脚本,以从网页中抓取不同咖啡店的名称和电话号码。尽管我在下面尝试的方法达到了目的,但脚本看起来确实很凌乱。使用pyppeteer
库创建for循环的理想方法是什么?
到目前为止,我已经写过:
import asyncio
from pyppeteer import launch
url = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA"
async def get_names(link):
wb = await launch(headless=True)
page = await wb.newPage()
await page.goto(link)
containers = await page.querySelectorAll('div.v-card')
for container in containers:
name = await container.querySelector('.business-name span')
phone = await container.querySelector('.phones')
post = await page.evaluate('(element) => element.textContent', name)
postAno = await page.evaluate('(element) => element.textContent', phone)
print(f'{post}--{postAno}')
await wb.close()
asyncio.get_event_loop().run_until_complete(get_names(url))
答案 0 :(得分:1)
我会这样:
import asyncio
from pyppeteer import launch
url = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA"
async def get_names(link):
wb = await launch()
page = await wb.newPage()
await page.goto(link)
containers = await page.querySelectorAll('div.v-card')
for container in containers:
name = await container.querySelectorEval('.business-name span','e => e.innerText')
phone = await container.querySelectorEval('.phones','e => e.innerText')
print(name,phone)
asyncio.get_event_loop().run_until_complete(get_names(url))
答案 1 :(得分:0)
尝试:
import asyncio
from pyppeteer import launch
url = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA"
async def get_names(link):
wb = await launch(headless=True)
page = await wb.newPage()
await page.goto(link)
names = await page.querySelectorAllEval('div.v-card .business-name span',
'(elements => elements.map(e => e.textContent))')
phones = await page.querySelectorAllEval('div.v-card .phones',
'(elements => elements.map(e => e.textContent))')
result = {name: phones[idx] for (idx, name) in enumerate(names)}
print(result)
await wb.close()
asyncio.get_event_loop().run_until_complete(get_names(url))
并阅读文档:querySelectorAllEval