Как изменять элементы сайта через Pyhhon
Я спарсил данные с сайта и создал новый файл parse.html. Не получается заменить ссылку на другую, как это можно сделать ?
import requests
from bs4 import BeautifulSoup
import webbrowser
import re
import urllib.request
link = 'http://127.0.0.1:5500/dat.html'
response = requests.get(link).text
with open('parse.html', 'w', encoding= 'utf-8') as file:
file.write(response)
soup = BeautifulSoup(response, 'lxml')
def links():
internalLinks = [
a.get('href')
for a in soup.find_all('a')
if a.get('href') and a.get('href').startswith('https://')]
return internalLinks
new_link = links()
print(*new_link, sep='\n')
"""Здесь нужно как то открыть файл parse.html и записать туда изменения"""
for a in soup.findAll('a'):
a['href'] = a['href'].replace("https://www.youtube.com/", "https://google.com/")
webbrowser.open('parse.html')
Файл dat.html имеет всего 2 ссылки
<a href="https://www.youtube.com/" target="_blank">youtube</a>
</h1>
<h1>
<a href="https://ru.wikipedia.org/wiki/" target="_blank">wiki</a>
</h1>
Ответы (1 шт):
Автор решения: Сергей Шашко
→ Ссылка
link = 'http://127.0.0.1:5500/dat.html'
response = requests.get(link).text
res = response.replace("https://www.youtube.com/", "https://google.com/")
with open('parse.html', 'w', encoding= 'utf-8') as file:
file.write(res)
webbrowser.open('parse.html')