首页 > 解决方案 > 如何在 Python 中仅从 Google 搜索页面获取链接?

问题描述

我尝试了很多方法,但都失败了。我能够获取链接,但不仅仅是域名。我希望 Google 将所有页面的域列表保存在一个文件中。例如:(https://www.google.com)。这是我的代码包括,也是我的输出图片。

import requests
from bs4 import BeautifulSoup
import re


class males:
    def googleurlcode(self):
        user_input = input("Enter something for Search : ")
        print("Wait...")

        google_search = requests.get("https://www.google.com/search?q=" + user_input)

        soup = BeautifulSoup(google_search.text, 'html.parser')

        search_results = soup.find_all("a")

        for link in search_results:
            print(re.split(":(?=http)", link["href"].replace("/url?q=", "")))


dahah = males()

while True:
    answer = input('Do you want to continue[y/n]?:')
    if answer.lower().startswith("y"):
        dahah.googleurlcode()
        # print("ok, carry on then")
    elif answer.lower().startswith("n"):
        print("ok, Good By")
        exit()
    

我的输出

标签: python

解决方案


使用urllib库打开链接,然后就可以获取域名了

def get_domain_name(link):
    OpenedPage = request.urlopen(request.Request(link,
                      headers={'User-Agent': 'Chrome'})).read().decode("utf-8")
    domain_name = BeautifulSoup(OpenedPage, "lxml") #.find('Domain_Name')
    return domain_name

推荐阅读