python实现批量自动访问站点URL并获取内容,自动模拟打开电脑端及移动端URL访问站点,打开URL页面获取页面内容

问题描述:假设目前有多个网站URL,需要检查各站点keyword,description是否正常设置,如果人工逐个打开URL访问比较耗时,故采用python模拟电脑端和移动端自动打开网站URL访问,并记录下访问的结果,最终人工查看结果,对其中未正常配置的站点进行单独处理。

准备工作:计算机已正常安装python,selenium,BeautifulSoup且能正常运行python程序,读者可自行搜索安装方法,在此不做赘述。

1.模拟电脑端循环打开URL检查示例代码(只提供基础逻辑处理演示,读者可根据自己的实际业务需求进行编写)

from bs4 import BeautifulSoup
from selenium import webdriver
import datetime
now = datetime.datetime.now()
fname=now.strftime('%Y%m%d%H%M')+".txt"            /*生成txt结果文档*/

def main(url):
driver = webdriver.Chrome()
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html)
title = soup.title.string
description = soup.find(attrs={"name": "description"})['content']
keywords = soup.find(attrs={"name": "keywords"})['content']
# print('title:', title)             
# print('description:', description)
# print('keywords:', keywords)

with open('G:\\FinalOutput\\'+fname, 'a', encoding='utf-8') as file:                /*设置txt文件保存路径并写入,其中参数a表示追加内容,如果为w,则为覆盖写入,此处用到循环,故设置为a参数*/
file.write(
"网址是:" +url + "\n" + "标题是 :" + title + "\n" + "描述是:" + description + "\n" + "关键词是:" + keywords + "\n\n")    /*输出内容设置编辑*/
urls = ['http://www.aaa.com', 'http://www.bbb.com’, 'http://www.ccc.com’]     /*需要访问的URL地址,需要加http或https,并能正常访问*/
for url in urls:                                                                                      /*循环打开访问URL*/
if __name__ == '__main__':
main(url)

 

2.模拟移动端循环打开URL检查示例代码(只提供基础逻辑处理演示,读者可根据自己的实际业务需求进行编写)

from selenium import webdriver
import datetime

now = datetime.datetime.now()
fname = now.strftime('%Y%m%d%H%M') + "MOBILE.txt"                       /*生成txt结果文档*/

def main(url):
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone X'})            /*模拟iPhone X浏览*/
driver = webdriver.Chrome(options=options)

driver.get(url)
page_source = driver.page_source
resp = page_source[20:600]                                                                             /*截取字符串,范围为20到600*/
with open('G:\\FinalOutput\\' + fname, 'a', encoding='utf-8') as file:              /*设置txt文件保存路径并写入,其中参数a表示追加内容,如果为w,则为覆盖写入,此处用到循环,故设置为a参数*/
file.write("网址是:" + url + "\n" + "结果是:" + resp + "\n\n")             /*输出内容设置编辑*/


urls = ['https://www.ggg.com./', 'http://www.fff.com/']                               /*需要访问的URL地址,需要加http或https,并能正常访问*/
for url in urls:                                                                                         /*循环打开访问URL*/
if __name__ == '__main__':
main(url)

posted @ 2023-11-18 11:37  没用的阿吉是剑神  阅读(200)  评论(0编辑  收藏  举报