【问题标题】:Unable to fetch an item from a webpage in the right way无法以正确的方式从网页中获取项目
【发布时间】:2018-06-11 15:33:38
【问题描述】:

当我运行我的脚本从网页获取电话号码时,该脚本以一种混乱的方式执行它。我正在粘贴我为实现相同目标而编写的两个不同脚本。

我想坚持使用 oneliner 解决方案(第二个脚本)。如何修改我的第二个脚本以摆脱第一个脚本所做的空白?他们的机器人以相同的方式工作,但为什么输出会有所不同?

Check out this website link

这几乎是准确的(只有一个空格出现):

from bs4 import BeautifulSoup
import requests

url = "replace with above link"

req = requests.get(url)
sauce = BeautifulSoup(req.text,"lxml")
for items in sauce.select_one("table[width='610']").select("tr"):
    for item in items.select("td"):
        if "phone" in item.text:
            print(item.find_next_sibling().get_text())

我希望我的脚本如下所示。它还会获取正确的项目,但会出现很多空格。

from bs4 import BeautifulSoup
import requests

url = "replace with above link"

req = requests.get(url)
sauce = BeautifulSoup(req.text,"lxml")
for items in sauce.select_one("table[width='610']").select("tr"):
    phone = [item.find_next_sibling().get_text() for item in items.select("td") if "phone" in item.text]
    print(phone)

我希望得到的结果(周围没有空格):

212 22 24 24 57

这是它嵌入该网站的方式:

<tr>
            <td height="20"><font color="#787878" size="2" face="Arial, Helvetica, sans-serif"><strong>Téléphone
              :</strong></font></td>
            <td><strong><font color="#919CBA" size="2" face="Arial, Helvetica, sans-serif">
              212 22 24 24 57              </font></strong></td>
          </tr>

【问题讨论】:

    标签: python python-3.x web-scraping


    【解决方案1】:

    可以使用strip() 删除字符串中的尾随和前导空格。

    对于第一个解决方案,只需这样做:

    phone = []
    
    for items in sauce.select_one("table[width='610']").select("tr"):
        for item in items.select("td"):
            if "phone" in item.text:
                numbers.append(item.find_next_sibling().text.strip())
    
    print(phone)
    

    第二个解决方案不起作用,因为您正在为循环的每次迭代创建和打印一个新列表。如果你想使用列表推导,你必须做同样的嵌套循环:

     phone = [item.find_next_sibling().get_text().strip() for items in sauce.select_one("table[width='610']").select("tr") for item in items.select("td") if "phone" in item.text]
    
     print(phone)
    

    我个人认为第一种选择更容易理解。

    【讨论】:

    • 我知道这是我可能得到的第一个可能的解决方案,因为我首先尝试过。 Hit this link 查看它产生的输出。
    • 抱歉,从未测试过代码。这是因为您正在为循环的每次迭代创建和打印一个列表。我已经相应地更新了答案。
    • 它与我的第一个脚本有什么不同?还是谢谢。
    • 您的第一个解决方案工作正常,除了不使用 strip()。您发布的第二个代码示例显然与您为循环的每次迭代创建和打印列表的方式不同。我也使用列表理解的解决方案更新了答案。
    • 没办法。你成功了。非常感谢。
    【解决方案2】:

    我无法检查或测试您的示例(我收到请求错误 urllib3) 我认为你需要尝试这样的事情:

    req = requests.get(url)
    sauce=BeautifulSoup(req.content,"html5lib")
    
    table=sauce.find("div",{"color":"#919CBA"})
    
    for rows in table:
        tabs=rows.find_all("tr")
        for trtag in tabs:
            phone.append(trtag.find("td"))
    
    print(phone)
    

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 2022-01-22
      • 2014-11-11
      • 1970-01-01
      • 2019-12-27
      • 2018-07-21
      • 1970-01-01
      • 2016-11-01
      相关资源
      最近更新 更多