Python无法用requests获取网页源码的解决方法

最近在抓取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")

总结

到此这篇关于Python无法用requests获取网页源码的文章就介绍到这了,更多相关requests获取网页源码内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python requests模块基础使用方法实例及高级应用(自动登陆,抓取网页源码)实例详解

    1.Python requests模块说明 requests是使用Apache2 licensed 许可证的HTTP库. 用python编写. 比urllib2模块更简洁. Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码. 在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得人性化,使用Requests可以轻而易举的完成浏览器可有的任何操作. 现代,国际化

  • Python3使用requests包抓取并保存网页源码的方法

    本文实例讲述了Python3使用requests包抓取并保存网页源码的方法.分享给大家供大家参考,具体如下: 使用Python 3的requests模块抓取网页源码并保存到文件示例: import requests html = requests.get("http://www.baidu.com") with open('test.txt','w',encoding='utf-8') as f: f.write(html.text) 这是一个基本的文件保存操作,但这里有几个值得注意的

  • Python无法用requests获取网页源码的解决方法

    最近在抓取http://skell.sketchengine.eu网页时,发现用requests无法获得网页的全部内容,所以我就用selenium先模拟浏览器打开网页,再获取网页的源代码,通过BeautifulSoup解析后拿到网页中的例句,为了能让循环持续进行,我们在循环体中加了refresh(),这样当浏览器得到新网址时通过刷新再更新网页内容,注意为了更好地获取网页内容,设定刷新后停留2秒,这样可以降低抓不到网页内容的机率.为了减少被封的可能,我们还加入了Chrome,请看以下代码: fro

  • 三种获取网页源码的方法(使用MFC/Socket实现)

    第一个方法是使用MFC里面的 <afxinet.h> 复制代码 代码如下: CString GetHttpFileData(CString strUrl){     CInternetSession Session("Internet Explorer", 0);     CHttpFile *pHttpFile = NULL;     CString strData;     CString strClip;     pHttpFile = (CHttpFile*)Ses

  • Python爬虫学习之获取指定网页源码

    本文实例为大家分享了Python获取指定网页源码的具体代码,供大家参考,具体内容如下 1.任务简介 前段时间一直在学习Python基础知识,故未更新博客,近段时间学习了一些关于爬虫的知识,我会分为多篇博客对所学知识进行更新,今天分享的是获取指定网页源码的方法,只有将网页源码抓取下来才能从中提取我们需要的数据. 2.任务代码 Python获取指定网页源码的方法较为简单,我在Java中使用了38行代码才获取了网页源码(大概是学艺不精),而Python中只用了6行就达到了效果. Python中获取网页

  • Python requests获取网页常用方法解析

    这篇文章主要介绍了Python requests获取网页常用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 主要记录使用 requests 模块获取网页源码的方法 class Crawler(object): """ 采集类 """ def __init__(self, base_url): self._base_url = base_url self._cookie = None se

  • python获取整个网页源码的方法

    1.Python中获取整个页面的代码: import requests res = requests.get('https://blog.csdn.net/yirexiao/article/details/79092355') res.encoding = 'utf-8' print(res.text) 2.运行结果 实例扩展: from bs4 import BeautifulSoup import time,re,urllib2 t=time.time() websiteurls={} de

  • Python实现的下载网页源码功能示例

    本文实例讲述了Python实现的下载网页源码功能.分享给大家供大家参考,具体如下: #!/usr/bin/python import httplib httpconn = httplib.HTTPConnection("www.baidu.com") httpconn.request("GET", "/index.html") resp = httpconn.getresponse() if resp.reason == "OK&quo

  • Android编程实现网络图片查看器和网页源码查看器实例

    本文实例讲述了Android编程实现网络图片查看器和网页源码查看器.分享给大家供大家参考,具体如下: 网络图片查看器 清单文加入网络访问权限: <!-- 访问internet权限 --> <uses-permission android:name="android.permission.INTERNET"/> 界面如下: 示例: public class MainActivity extends Activity { private EditText image

  • asp.net 抓取网页源码三种实现方法

    方法1 比较推荐 /// <summary> /// 用HttpWebRequest取得网页源码 /// 对于带BOM的网页很有效,不管是什么编码都能正确识别 /// </summary> /// <param name="url">网页地址" </param> /// <returns>返回网页源文件</returns> public static string GetHtmlSource2(strin

  • Android 网络图片查看器与网页源码查看器

    在AndroidManifest.xml里面先添加权限访问网络的权限: <uses-permission android:name="android.permission.INTERNET"/> 效果图如下: 下面是主要代码: package com.hb.neting; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.ann

随机推荐