获取第一个点击的网址

2024-03-29 02:25:24 发布

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

我有一个谷歌查询,我想得到第一个点击的网址一串。你知道吗

我的一段代码:

import requests

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

然后我想检索的是第一个google热门网站,在本例中是Wikipedia页面:https://en.wikipedia.org/wiki/%22Hello,_World!%22_program

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


Tags: 代码importcomhttpurlhelloworldsearch
3条回答

您可以使用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

我建议使用像BeautifulSoup这样的东西来针对包含结果的URL的HTML元素。然后,你可以储存网址,并做你喜欢的。你知道吗

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'))

您可以使用“选择一个”来限制第一个匹配。使用类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'])

相关问题 更多 >