【问题标题】:Trying to find if certain text exists试图查找是否存在某些文本
【发布时间】:2019-11-18 04:06:07
【问题描述】:

我正在尝试查看我正在抓取的网站的个人资料页面上是否存在“国家注册”文字。它就在文本“许可工作:”之后......如果它包含文本,我会将他们的许可证类型写入 csv 文件作为“国家注册”,如果该文本不存在,我将为csv 文件中的许可证...这就是我正在使用的问题/编码逻辑

这是我正在测试我的代码的个人资料页面的链接 https://www.zillow.com/lender-profile/zackdisinger/

它一直打印错误...下面是我正在尝试的代码

from selenium import webdriver
from bs4 import BeautifulSoup
import time

#Chrome webdriver filepath...Chromedriver version 74
driver = webdriver.Chrome(r'C:\Users\mfoytlin\Desktop\chromedriver.exe')
page = driver.get('https://www.zillow.com/lender-profile/zackdisinger/')
time.sleep(2)
show_more_button = driver.find_element_by_class_name('zsg-wrapper-footer').click()
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')


if soup.find(text='Nationally registered'):
    print('Success')
else:
    print('False')

【问题讨论】:

  • 你能分享一下它给出的文本不存在或其他什么的确切错误
  • 文本在您链接的那个网址上的位置。我找到了...在 google chrome 中搜索“已注册”并且没有点击。
  • 无论@Ankit Agrawal 有什么,它都会打印错误
  • 你必须点击页面上的显示更多按钮才能看到许可@probat

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

使用 bs4 4.7.1,您可以使用 :contains 检查包含该字符串的 p 标签。虽然很容易适应 Success/False,但我给出了 True/False

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#Chrome webdriver filepath...Chromedriver version 74
driver = webdriver.Chrome(r'C:\Users\mfoytlin\Desktop\chromedriver.exe')
page = driver.get('https://www.zillow.com/lender-profile/zackdisinger/')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".zsg-wrapper-footer a"))).click()
soup = BeautifulSoup(driver.page_source, 'html.parser')
data = soup.select_one('p:contains("Nationally registered")')
print(data is not None)

【讨论】:

    【解决方案2】:

    使用正则表达式re检查文本是否存在。这是您的代码。

    from selenium import webdriver
    from bs4 import BeautifulSoup
    import time
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import re
    
    #Chrome webdriver filepath...Chromedriver version 74
    driver = webdriver.Chrome(r'C:\Users\mfoytlin\Desktop\chromedriver.exe')
    page = driver.get('https://www.zillow.com/lender-profile/zackdisinger/')
    show_more_button =WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'Show')][contains(.,'more')]")))
    #driver.execute_script("arguments[0].click();", show_more_button)
    show_more_button.click()
    time.sleep(2)
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    
    
    if soup.find(text=re.compile('Nationally registered')):
        print('Success')
    else:
        print('False')
    

    控制台打印成功。

    Success
    

    【讨论】:

      【解决方案3】:

      试试这样的条件块,

      if(driver.findElement(By.xpath("//p[contains(text(),'Nationally registered')]").isDisplayed())
      {
       print('Success')
      }
      else {
      print ('False')
      }
      

      【讨论】:

        【解决方案4】:

        数据通过 AJAX 从不同的 URL 加载:

        import re
        import requests
        import json
        
        url = 'https://www.zillow.com/lender-profile/zackdisinger/'
        screen_name = [i for i in url.split('/') if i][-1]
        r = requests.get(url).text
        
        url_json = 'https://mortgageapi.zillow.com/getRegisteredLender?partnerId=' + re.search(r'"partnerId":"(.*?)"', r).group(1)
        payload = {"fields":["aboutMe","address","cellPhone","contactLenderFormDisclaimer","companyName","employerMemberFDIC","employerScreenName","equalHousingLogo","faxPhone","hideCellPhone","imageId","individualName","languagesSpoken","memberFDIC","nationallyRegistered","nmlsId","nmlsType","officePhone","rating","screenName","stateLicenses","stateSponsorships","title","totalReviews","website"],"lenderRef":{"screenName":screen_name}}
        data = requests.post(url_json, json=payload).json()
        print(json.dumps(data, indent=4))
        print()
        print('Is nationally registered =', data['lender']['nationallyRegistered'])
        

        打印:

        {
            "lender": {
                "aboutMe": "From day one I provide the utmost relational-based experience to make you feel comfortable with your home financing decisions.\n\nEmpowerment and integrity is key to successfully making a home loan a smooth process from start to finish. Acquiring a mortgage in today's market takes product knowledge and underwriting know how. Every client has their own story, their own future. I am here to match today's mortgages to clients dreams of home-ownership.\n",
                "address": {
                    "address": "10412 Allisonville Rd Suite 50",
                    "city": "Fishers",
                    "stateAbbreviation": "IN",
                    "zipCode": "46038"
                },
                "companyName": "Bank of England Mortgage",
                "employerMemberFDIC": true,
                "employerScreenName": "BoEMortgage",
                "equalHousingLogo": "EqualHousingLender",
                "faxPhone": {
                    "areaCode": "317",
                    "number": "3754",
                    "prefix": "536"
                },
                "id": "ZU101hnzx7ntuyx_8z2sb",
                "imageId": "2910837992a9cc44d31c26bd7532d2dd",
                "individualName": {
                    "firstName": "Zachary",
                    "lastName": "Disinger"
                },
                "languagesSpoken": [],
                "nationallyRegistered": true,
                "nmlsId": 1053091,
                "nmlsType": "Individual",
                "officePhone": {
                    "areaCode": "317",
                    "number": "0416",
                    "prefix": "252"
                },
                "rating": 5.0,
                "screenName": "zackdisinger",
                "stateLicenses": {},
                "stateSponsorships": {},
                "title": "Mortgage Banker",
                "totalReviews": 120,
                "website": "http://boeindy.com"
            }
        }
        
        Is nationally registered = True
        

        【讨论】:

        • json 对我来说看起来像是一门外语,因为我刚刚开始并且只熟悉 bs4 和 selenium...任何链接/建议可以开始/熟悉使用这种方法? @Andrej Kesely
        • @mcfoyt 这与 JSON 无关。只是观察发出请求的页面在哪里,例如通过 Chrome 开发者工具的 Firefox。
        猜你喜欢
        • 2018-03-25
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多