【问题标题】:Using Beautifulsoup and Selenium to get links from a webpage with certain words使用 Beautifulsoup 和 Selenium 从包含特定单词的网页中获取链接
【发布时间】:2015-05-21 20:06:57
【问题描述】:

我编写此代码是为了登录我的 FB 帐户并使用 Selenuim 和 BeautifulSoup 获取页面上的所有群组链接,但 BeautifulSoup 的使用无法正常工作。

我想知道如何在同一代码中使用 Selenuim 和 BeautifulSoup。

我不想使用 Facebook API;我想使用 Selenium 和 BeautifulSoup。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer


usr = raw_input('--> ')
pwd = raw_input('--> ')
poo = raw_input('--> ')

driver = webdriver.Firefox()
# or you can use Chrome(executable_path="/usr/bin/chromedriver")
driver.get("https://www.facebook.com/groups/?category=membership")
assert "Facebook" in driver.title
elem = driver.find_element_by_id("email")
elem.send_keys(usr)
elem = driver.find_element_by_id("pass")
elem.send_keys(pwd)
elem.send_keys(Keys.RETURN)

scheight = .1
while scheight < 9.9:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight/%s);" % scheight)
    scheight += .01
soup = BeautifulSoup(html)
http = httplib2.Http()
status, response = ('https://www.facebook.com/groups/?category=membership')

count = 0
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
     count = count + 1
print 'Count: ', count 

for tag in BeautifulSoup(('a')):
    if link.has_key('href'):
        if '/groups/' in link['href']:

          print link['href']


elem = driver.find_element_by_css_selector(".input.textInput")
elem.send_keys(poo)
elem = driver.find_element_by_css_selector(".selected")
elem.send_keys(Keys.RETURN)
elem.click()
time.sleep(5)

【问题讨论】:

  • 你需要澄清一下。 “漂亮的汤不能正常工作”是什么意思?会发生什么,这与期望的行为有何不同?
  • 结果 Traceback(最近一次调用最后一次):文件“tk.py”,第 28 行,在 soup = BeautifulSoup(html) NameError: name 'html' is not defined跨度>

标签: python selenium-webdriver beautifulsoup desktop-application


【解决方案1】:

你从未声明过html

Selenium 的 webdriver 有一个 page_source 可以使用的方法:

soup = BeautifulSoup(driver.page_source)

更新第二个错误

你的电话,

status, response = ('https://www.facebook.com/groups/?category=membership')

正在尝试将该字符串分配给statusresponse。没有什么可以分配给 response,因此该变量是未定义的。

【讨论】:

  • Traceback(最近一次调用最后一次):文件“tk.py”,第 33 行,在 中用于 BeautifulSoup 中的链接(响应,parseOnlyThese=SoupStrainer('a')):NameError:名称“响应”未定义
  • 更新了第二个错误。您是从某个地方复制此代码还是正在编写它?
  • 所以你的意思是我应该删除这一行?
【解决方案2】:

我认为 BeautifulSoup 没有返回链接吗?

我确实在 BeautifulSoup 中找到了链接

soup = BeautifulSoup( html )
for i in soup.find_all( 'a' ):
if '/groups/' in i.get( 'href' ):
    print( i.get( 'href' ) )

【讨论】:

  • soup = BeautifulSoup(html) NameError: name 'html' is not defined
  • Traceback(最近一次调用最后一次):文件“tk.py”,第 43 行,在 中 for i in soup.find_all('a'): TypeError: 'NoneType' object is not可调用
  • 意味着它从未在页面或 html 变量上找到任何链接
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 2013-11-02
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2018-03-26
相关资源
最近更新 更多