得到第一个网页的网址[网络抓python]

问题描述 投票:0回答:3

我有一堆谷歌查询,我想获得第一次点击的网址。

我的一段代码:

import requests

query = 'hello world'
url = 'http://google.com/search?q=' + query
page= requests.get(url)
print(url)

那么我想要检索的是第一个谷歌网站,在这个案例中,维基百科页面:https://en.wikipedia.org/wiki/%22Hello,_World!%22_program

我有其余的代码,但我不知道如何检索网址。

python url web-scraping
3个回答
0
投票

您可以使用select_one限制首次匹配。使用类r限制结果。使用类和类型选择器比使用属性更快,这就是我使用ra的原因。

import requests
from bs4 import BeautifulSoup as bs
query = 'hello world'
url = 'http://google.com/search?q=' + query
page= requests.get(url)
soup = bs(page.content, 'lxml')
print(soup.select_one('.r a')['href'])

0
投票

我建议使用Beautiful Soup之类的东西来定位包含结果URL的HTML元素。然后,您可以存储URL并随意使用它。

import requests
from bs4 import BeautifulSoup

query = 'hello world'
url = 'http://google.com/search?q=' + query
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))

0
投票

您可以使用BeautifulSoup查找Web结果,然后找到返回href的第一个元素:

import requests
import bs4

query = 'hello world'
url = 'http://google.com/search?q=' + query

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
page= requests.get(url, headers=headers)

soup = bs4.BeautifulSoup(page.text, 'html.parser')

for elem in soup(text='Web results'):
    print (elem.find_next('a')['href'])

输出:

print (elem.find_next('a')['href'])


https://en.wikipedia.org/wiki/%22Hello,_World!%22_program
© www.soinside.com 2019 - 2024. All rights reserved.