0
Follow
2
View

How can I modify this html file in python?

cuixiao8765 注册会员
2023-01-26 06:35

When it throws AttributeError: 'NoneType' object has no attribute 'replace_with' error, this means that it couldn't find the string you wanted in the text so the find() function, returned None and absolutely None doesn't have replace_with attribute.
Do this to prevent the error:

[...]
old=d.findAll("a",{"title":"Series"})
for n in range(129):
    for i in old:
        try:
            new=i.find(text=re.compile(f"PAT-204635 - LAICHE AHMED ILYES - Number {n}")).replace_with (f"PAT-204635 - LAICHE MOHAMED ISLAM - Number {n}")
        except:
            continue
[...]
w13811551210 注册会员
2023-01-26 06:35

From what I understand from your question, you want to replace

with

You can try this out.

from bs4 import BeautifulSoup
import re
d = """

          PAT-204635 - LAICHE AHMED ILYES - Number 4
         

          PAT-204635 - LAICHE AHMED ILYES - Number 56
         

          PAT-204635 - LAICHE AHMED ILYES - Number 9
         

          PAT-204635 - LAICHE AHMED ILYES - Number 77
         
"""
soup = BeautifulSoup(d, 'lxml')
old = soup.findAll("font",{"color":"#FFFFFF"})
new= soup.find_all(text=re.compile(r"PAT-204635 - LAICHE AHMED ILYES - Number \d+\b"))
for i in new:
    num = i.strip().split(' ')[-1]
    i = i.replace_with (f"PAT-204635 - LAICHE MOHAMED ISLAM - Number {num}")
        
print(soup.prettify())

This is how the final HTML code looks like.

<html>
 

   PAT-204635 - LAICHE MOHAMED ISLAM - Number 4
  

   PAT-204635 - LAICHE MOHAMED ISLAM - Number 56
  

   PAT-204635 - LAICHE MOHAMED ISLAM - Number 9
  

   PAT-204635 - LAICHE MOHAMED ISLAM - Number 77