【问题标题】:Search for text by re.search from different locations in HTML通过 re.search 从 HTML 中的不同位置搜索文本
【发布时间】:2021-04-06 23:52:49
【问题描述】:

我正在尝试编写一个条件语句来搜索电子邮件:

  • 用户简介
  • 如果在用户信息中没有找到搜索
  • elif 未找到,因为它可能缺少返回类似“N/A”的内容

我尝试了多种方法,但要么收到错误 AttributeError: 'NoneType' object has no attribute 'group',要么没有得到想要的结果。

这是我正在尝试做的一个示例:

email_list = []

url = input("Link")

r = requests.get(url, timeout=30)
soup = BeautifulSoup(r.text, 'html.parser')
name_array = soup.find_all('h1', {'class': 'class1'})

bio = soup.find('div', {'class': 'UserBio'}).text
info=soup.find('div', {'class': 'UserInfo'}).text

try:
    email = re.search('\S+@\S+', bio).group()
    print(email+"bio")
except AttributeError as e:
    print(e)
try:
    email = re.search('\S+@\S+', info).group()
    print(email + "info")
except AttributeError as e:
    print(e)
print(email)
email_list.append(email)

我使用 Try except 的原因是生成了一个错误作为属性错误。

我想要的结果是:

  1. 在用户简介中搜索电子邮件
  2. 如果在用户信息中搜索电子邮件的用户简历中不可用。
  3. 如果用户信息中无法将其附加为“N/A”

【问题讨论】:

    标签: python beautifulsoup python-re


    【解决方案1】:

    如果不匹配,search() 函数可以返回 None。所以如果你没有匹配你的搜索行是有效的:

    email = None.group()
    

    您需要在调用方法之前检查搜索结果为 None 如果不是 none 以获取电子邮件信息。

    【讨论】:

      【解决方案2】:

      我能够找到问题的解决方案,所以我想贡献它: 在用户简介中搜索电子邮件:

      while email_found == None:
              if soup.find_all(class_="UserBio"):
                  for my_tag in soup.find_all(class_="UserBio"):
                      emails = re.findall(EMAIL_REGEX, my_tag.text)
                      email = None if not emails else emails
                      if email != None:
                          print(email)
                          email_list.append(email[0])
                          print(email_list, "1")
                          email_found = True
                      break
                  else:
                      email = None
                      print("None 1 in UserBio")
              else:
                  email=None
                  print("None 1 in User Info 1")
              if soup.find('a', {'class': 'UserInfo'}):
                  EMAIL_REGEX = "[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
                  new_soup = BeautifulSoup(new_r.text, 'html.parser')
                  email_elements = new_soup.find('a', {'class':'link'}).text.strip().split()
                          email=email_elements[0]
                          email_list.append(email)
                          print(email_list, "3")
                          email_found = True
                          break
              else:
                  email = None
                  break
          if email_found == None:
              email = "N/A"
              email_list.append(email)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-16
        相关资源
        最近更新 更多