Python无法用requests获取网页源码的解决方法
作者:henanlion 发布时间:2023-04-24 07:38:04
最近在抓取http://skell.sketchengine.eu网页时,发现用requests无法获得网页的全部内容,所以我就用selenium先模拟浏览器打开网页,再获取网页的源代码,通过BeautifulSoup解析后拿到网页中的例句,为了能让循环持续进行,我们在循环体中加了refresh(),这样当浏览器得到新网址时通过刷新再更新网页内容,注意为了更好地获取网页内容,设定刷新后停留2秒,这样可以降低抓不到网页内容的机率。为了减少被封的可能,我们还加入了Chrome,请看以下代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from bs4 import BeautifulSoup
import time,re
path = Service("D:\\MyDrivers\\chromedriver.exe")#
# 配置不显示浏览器
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36')
# 创建Chrome实例 。
driver = webdriver.Chrome(service=path,options=chrome_options)
lst=["happy","help","evening","great","think","adapt"]
for word in lst:
url="https://skell.sketchengine.eu/#result?lang=en&query="+word+"&f=concordance"
driver.get(url)
# 刷新网页获取新数据
driver.refresh()
time.sleep(2)
# page_source——》获得页面源码
resp=driver.page_source
# 解析源码
soup=BeautifulSoup(resp,"html.parser")
table = soup.find_all("td")
with open("eps.txt",'a+',encoding='utf-8') as f:
f.write(f"\n{word}的例子\n")
for i in table[0:6]:
text=i.text
#替换多余的空格
new=re.sub("\s+"," ",text)
#写入txt文本
with open("eps.txt",'a+',encoding='utf-8') as f:
f.write(re.sub(r"^(\d+\.)",r"\n\1",new))
driver.close()
1. 为了加快访问速度,我们设置不显示浏览器,通过chrome.options实现
2. 最近通过re正则表达式来清理格式。
3. 我们设置table[0:6]来获取前三个句子的内容,最后显示结果如下。
happy的例子
1. This happy mood lasted roughly until last autumn.
2. The lodging was neither convenient nor happy .
3. One big happy family "fighting communism".
help的例子
1. Applying hot moist towels may help relieve discomfort.
2. The intense light helps reproduce colors more effectively.
3. My survival route are self help books.
evening的例子
1. The evening feast costs another $10.
2. My evening hunt was pretty flat overall.
3. The area nightclubs were active during evenings .
great的例子
1. The three countries represented here are three great democracies.
2. Our three different tour guides were great .
3. Your receptionist "crew" is great !
think的例子
1. I said yes immediately without thinking everything through.
2. This book was shocking yet thought provoking.
3. He thought "disgusting" was more appropriate.
adapt的例子
1. The novel has been adapted several times.
2. There are many ways plants can adapt .
3. They must adapt quickly to changing deadlines.
补充:经过代码的优化以后,例句的爬取更加快捷,代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from bs4 import BeautifulSoup
import time,re
import os
# 配置模拟浏览器的位置
path = Service("D:\\MyDrivers\\chromedriver.exe")#
# 配置不显示浏览器
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36')
# 创建Chrome实例 。
def get_wordlist():
wordlist=[]
with open("wordlist.txt",'r',encoding='utf-8') as f:
lines=f.readlines()
for line in lines:
word=line.strip()
wordlist.append(word)
return wordlist
def main(lst):
driver = webdriver.Chrome(service=path,options=chrome_options)
for word in lst:
url="https://skell.sketchengine.eu/#result?lang=en&query="+word+"&f=concordance"
driver.get(url)
driver.refresh()
time.sleep(2)
# page_source——》页面源码
resp=driver.page_source
# 解析源码
soup=BeautifulSoup(resp,"html.parser")
table = soup.find_all("td")
with open("examples.txt",'a+',encoding='utf-8') as f:
f.writelines(f"\n{word}的例子\n")
for i in table[0:6]:
text=i.text
new=re.sub("\s+"," ",text)
with open("eps.txt",'a+',encoding='utf-8') as f:
f.write(new)
# f.writelines(re.sub("(\.\s)(\d+\.)","\1\n\2",new))
if __name__=="__main__":
lst=get_wordlist()
main(lst)
os.startfile("examples.txt")
来源:https://blog.csdn.net/henanlion/article/details/122757040
猜你喜欢
- 什么是分页查询分页查询就是把query到的结果集按页显示。比如一个结果集有1W行,每页按100条数据库。而你获取了第2页的结果集。为什么要分
- 在技术问答中看到一个这样的问题,感觉相对比较常见,就单开一篇文章写下来。从纯文本格式文件 “file_in”中读取数据,格式如下:需要输出成
- 如下所示:from pymongo import MongoClient#建立和数据库系统的连接,指定host及port参数client =
- python内存管理机制:引用计数垃圾回收内存池1. 引用计数当一个python对象被引用时 其引用计数增加 1 ; 当其不再被变量引用时
- 本文实例讲述了Python实现的将文件每一列写入列表功能。分享给大家供大家参考,具体如下:# -*- coding: utf-8 -*-#!
- 方法一、尽量使用复杂的SQL来代替简单的一堆 SQL.同样的事务,一个复杂的SQL完成的效率高于一堆简单SQL完成的效率。有多个查询时,要善
- 前提条件:1.安装好Wampserver64(版本不限)2.Wampserver64软件启动后 变为绿色如:3.在数据库里面创建好名为&am
- 看下面的Java代码,目的是为了当i是3的时候,就不做输出,直接跳到下一个循环。int i = 0; 
- 使用ewebeditor作为后台编辑器时,尤其是一个页面中使用多次该编辑器时,在提交数据时,可能会遇到数据被重复提交的情况。搜索找来一些解决
- ORA-00600:internal error code,arguments:[num],[?],[?],[?],[?] 产生原因:这种错
- 锚点是“top”,可以放在页面的任何位置,一般是页首。程序就是对锚点出现的判断,我设置的数值是4,意思是出现4个动态数据就出现一个锚点,少于
- 目录列表拼接三种方式方式一:简简单单的“+”方法二:切片赋值方式三:列表自带的extend()列表去重的三种方式利用集合set的特性利用字典
- 1、给滚动条换色 好多网站的滚动条不是系统默认的灰色,而是一些红色、蓝色的,请问这是如何做的?答:这个很好实现,插入下面的代码:<&n
- //-------------------------------------------- // 删除千分点。 //-----------
- 创建一个表T_Employee并插入若干数据 代码如下:create table T_Employee(FNumber VARC
- 前言学学Python中操纵JSON的知识。学完本文,你可以学到如下内容:1、JSON是什么?2、JSON与XML的优劣差异?3、将Pytho
- 说明字符串驻留是一种仅保存一份相同且不可变字符串的方法。不同的值被存放在字符串驻留池中,发生驻留之后, 许多变量可能指向内存中的相同字符串对
- 本文实例讲述了Python图形绘制操作之正弦曲线实现方法。分享给大家供大家参考,具体如下:要画正弦曲线先设定一下x的取值范围,从0到2π。要
- 张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。张量类似于Nu
- 请问如何使用CDONTS组件来发送电子邮件?我们可以在IIS4下使用CDONTS来完成。首先要确认是否安装了SMTP服务(OPTIONPAC