python - 如何在 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()
解决方案
使用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
推荐阅读
- c++ - 应用程序崩溃后实现文件恢复的概念(例如 SIGSEGV)
- sql - 比较两个不同但结构相同的数据库中的两个表未返回预期结果
- reactjs - 无法使用 typescript 从 redux 工具包访问数据
- java - 如何使用给定的类从字符串数组实现二叉树,然后对其进行序列化、反序列化和遍历?
- arrays - 没有正确打印数组的值(非常初学者编程)
- docker - 如何将应用程序打包到能够在 Kubernetes 中的 Spark 集群上运行的 docker 镜像中?
- python - 如何在 tkinter 中创建一个全局变量?
- java - 如何在 Java 中处理陈旧的池连接
- apache - 通过 Apache 将特定用户代理限制为 Internet Explorer?
- javascript - 最初填充的道具值,然后不在反应js中