【问题标题】:Python BeautifulSoup web scrapingPython BeautifulSoup 网页抓取
【发布时间】:2017-09-20 12:16:26
【问题描述】:

嗨,我是 python 和网络抓取的新手,以下是我从网站获取 URL 的脚本,但我被困在两者之间,如果我检查网站,我无法从类标签中获取 URL,我可以看到 URL,但是在我的脚本中它显示为 javascript This is the link 任何帮助,请 提前致谢

from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
url = "https://www.northcoastelectric.com/Products"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
something = soup.find(class_="clearAfter")
print(chips)
for i in something:
   new_url = i.a["href"]
   print(new_url)`

【问题讨论】:

  • 具体是什么网址?你能提供一个你需要的样本吗
  • 我需要网站中存在的产品 URL,就像有产品自动化和电机控制一样我需要该页面中所有产品的 URL

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


【解决方案1】:

你应该用cimm_categoryItemBlock 代替clearAfter find_all 类名,因为那是包含产品链接的li 的类名

something = soup.find_all(class_="cimm_categoryItemBlock")
for i in something:
    new_url = i.a.get("href")
    print(new_url)

【讨论】:

  • 如果它解决了您的问题,请将此标记为答案。谢谢!
  • 我使用您的代码得到了结果。你能告诉我为什么我的代码在这行代码中出错了 "chips = soup.find(class_="clearAfter").find_all('li') for i in chips: potato = i.a["href"] print(potato )"
  • 因为find() 只返回找到的第一个元素,但find_all() 返回具有该类的所有元素
【解决方案2】:

你只需要再深入一层。试试这个:

something = soup.find(class_="clearAfter").findNext("clearAfter")

只需继续添加与上面完全相同的“findNext”命令到“something”变量(假设每个链接的类名相同),您就会到达链接。

记住:Beautifulsoup(和 HTML)可以有很多分支。当您创建 Beautifulsoup 的实例时,常见的说法是您正在创建一个新的“树”。那么,如果一切都失败了呢?只需创建另一个实例并尝试不同的分支/不同的方式(你可能在这里不需要),你就会很成功。 HTML 可以非常嵌入。

否则,您可以使用硒。超级简单:

只需使用 selenium 命令按名称(在您的情况下为 clearAfter)收集页面上的所有类,对其进行迭代,附加到列表并通过“get_attribute”方法获取 href。这是我如何使用 selenium 执行此操作的示例。

    def get_results(self):
        cv = []
        bbb = self.driver.find_elements_by_class_name('user-name') ## self.driver is my Chromedriver webdriver used to manipulate the browser. Let me know if you have Qs!

    for plink in bbb:
           cv.append(plink.find_element_by_css_selector(
                              'a').get_attribute('href'))

希望我能帮上忙。

【讨论】:

  • 谢谢你,Aaron Brandhagen,但之前的回答解决了这个问题
猜你喜欢
  • 2018-04-25
  • 2014-06-20
  • 1970-01-01
  • 2014-06-20
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多