【问题标题】:Using Python to Parse a Web Page使用 Python 解析网页
【发布时间】:2020-09-02 08:16:17
【问题描述】:

我对 Python 完全陌生,真的需要一些帮助。

我正在尝试解析网页并从网页中检索电子邮件地址。 我尝试了很多我在网上阅读的东西,但都失败了。

我意识到,在运行 BeautifulSoup(browser.page_source) 时,它会带来源代码,但由于某种原因,它并没有带来电子邮件地址或业务资料。

下面是我的代码(不要评判:-))

import os, random, sys, time

from urllib.parse import urlparse

from selenium import webdriver

from bs4 import BeautifulSoup

from webdriver_manager.chrome import ChromeDriverManager

import lxml

browser = webdriver.Chrome('./chromedriver.exe')

url = ('https://www.yellowpages.co.za/search?what=accountant&where=cape+town&pg=1')
browser.get(url)

BeautifulSoup(browser.page_source)

旁注:我的目标是根据搜索条件浏览网页并解析每个页面的电子邮件地址,我已经弄清楚如何浏览网页并发送密钥,这只是我坚持的解析。 非常感谢您的帮助

【问题讨论】:

标签: python html parsing web-scraping beautifulsoup


【解决方案1】:

我推荐你使用requests模块到get页面源:

from requests import get

url = 'https://www.yellowpages.co.za/search?what=accountant&where=cape+town&pg=1'
src = get(url).text  # Gets the Page Source

之后我搜索了电子邮件格式的单词并将它们添加到列表中:

src = src.split('<body>')[1]  # Splits it and gets the <body> part

emails = []

for ind, char in enumerate(src):
    if char == '@':
        add = 1  # Count the characteres after and before
        new_char = src[ind+add]  # New character to add to the email
        email = char  # The full email (not yet)

        while new_char not in '<>":':
            email += new_char  # Add to email

            add += 1                   # Readjust
            new_char = src[ind + add]  # Values

        if '.' not in email or email.endswith('.'):  # This means that the email is 
            continue                                 # not fully in the page

        add = 1                    # Readjust
        new_char = src[ind - add]  # Values

        while new_char not in '<>":':
            email = new_char + email  # Add to email

            add += 1                   # Readjust
            new_char = src[ind - add]  # Values

        emails.append(email)

最后,您可以使用set 删除重复邮件并打印邮件

emails = set(emails)  # Remove Duplicates

print(*emails, sep='\n')

【讨论】:

  • 谢谢拉斐尔,我试了一下,同样的事情发生了。似乎当我打印源代码时,它遗漏了包含所有电子邮件地址的整个第一部分,只打印最后一部分。有什么建议吗?
  • “最后一部分”是什么意思?
  • 实际网页上的源代码基本上一共有3060行代码。当我们使用 Python 解析源代码时,它只需要从第 1760 行到第 3060 行的源代码
猜你喜欢
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2012-06-29
  • 1970-01-01
  • 2016-04-14
  • 2013-02-09
  • 2017-07-29
相关资源
最近更新 更多