1. 本际云推荐 - 专业推荐VPS、服务器,IDC点评首页
  2. 云主机运维
  3. VPS运维

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

如何解决Python无法用requests获取网页源码的问题

作为互联网时代的一份子,我们总是会遇到各种各样的困惑和麻烦,比如Python无法用requests获取网页源码的问题。这不仅会影响我们的工作效率,还会耽误我们的宝贵时间。

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

解决方法

最近,在抓取 http://skell.sketchengine.eu 网页时,我遇到了使用requests无法获得网页全部内容的问题。为了解决这个问题,我用selenium模拟浏览器打开网页,再获取网页的源代码,并通过BeautifulSoup解析获取到网页中的例句。具体实现的代码如下:

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()

为了加快访问速度,我们设置不显示浏览器,并通过chrome.options实现。同时,使用re正则表达式来清理格式,提高获取网页内容的准确性。值得注意的是,为了减少被封的可能,我们还加入了Chrome浏览器。最后,我们通过以上的代码,可以成功获取到例句,并将其保存到eps.txt文本中。

优化代码

针对代码的一些不足,例如速度较慢、容易卡顿等问题,我们进行了代码的优化,使例句的爬取更加快速。同时,我们通过修改程序配置文件,使程序可以读取txt格式的单词列表,提高了代码的灵活性和实用性。具体代码如下:

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)
    
        driver.close()

if __name__=="__main__":
    lst=get_wordlist()
    main(lst)
    os.startfile("examples.txt")

通过对代码的优化,我们成功提高了程序运行的速度和稳定性,更好地实现了获取网页源码的目的。

以上就是关于Python无法用requests获取网页源码的问题的解决方案,希望可以为大家提供一些帮助。

原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7362.html