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

标签:requests,网页,源码
0
投稿

猜你喜欢

  • 详解Python中string模块除去Str还剩下什么

    2021-08-25 12:48:19
  • 让JavaScript拯救HTML5的离线存储[译]

    2009-05-15 12:26:00
  • PHP实现用户认证及管理完全源码

    2023-11-19 20:26:19
  • 在python的WEB框架Flask中使用多个配置文件的解决方法

    2023-09-05 03:56:54
  • PHP PDOStatement::rowCount讲解

    2023-06-06 12:24:04
  • Go 语言进阶freecache源码学习教程

    2023-08-06 03:05:20
  • FCKeditor编辑器基本配置优化修改使用方法

    2008-12-31 13:32:00
  • Python Tornado批量上传图片并显示功能

    2023-08-07 22:33:21
  • 详解OpenCV实现特征提取的方法

    2022-10-05 11:15:28
  • 对python3 Serial 串口助手的接收读取数据方法详解

    2023-05-31 17:39:01
  • 利用Python写一个爬妹子的爬虫

    2021-07-22 12:44:51
  • Python3 实现随机生成一组不重复数并按行写入文件

    2021-11-25 18:05:35
  • 两组字符串数据比较合并相同数据

    2008-07-31 17:27:00
  • 4个Web图片在线压缩优化工具

    2009-10-13 21:02:00
  • Python实现壁纸下载与轮换

    2022-07-01 19:19:19
  • XML to DDL的项目关键:与数据库同步

    2008-05-29 14:19:00
  • Django模板获取field的verbose_name实例

    2023-07-30 06:53:55
  • 面向对象设计过程中必须遵守的相关准则

    2009-01-08 15:52:00
  • python3中编码获取网页的实例方法

    2023-07-17 23:31:47
  • python必学知识之文件操作(建议收藏)

    2021-10-01 16:28:25
  • asp之家 网络编程 m.aspxhome.com