使用Selenium和beautifulsoup进行网络抓取代码无法正常工作

时间:2019-06-18 04:30:59

标签: selenium beautifulsoup python-3.7

我写了python代码,用于网上抓取《悉尼先驱晨报》。此代码首先单击所有的显示更多按钮,然后抓取所有文章。硒部分正常工作。但是我认为在抓取部分存在一些问题,因为在为几篇文章(5-6)抓取所需字段(日期,标题和内容)之后,它只给出了日期和标题,没有内容。

import time
import csv
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

base = 'https://www.smh.com.au'
browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
wait = WebDriverWait(browser, 10)
browser.get('https://www.smh.com.au/search?text=cybersecurity')

while True:
    try:
        time.sleep(2)
        show_more = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, '_3we9i')))
        show_more.click()
    except Exception as e:
            print(e)
            break

soup = BeautifulSoup(browser.page_source,'lxml')
anchors = soup.find_all('a', {'tabindex': '-1'})
for anchor in anchors:
    browser.get(base + anchor['href'])
    sub_soup = BeautifulSoup(browser.page_source, 'html.parser')
    dateTag = sub_soup.find('time', {'class': '_2_zR-'})
    titleTag = sub_soup.find('h1', {'itemprop': 'headline'})
    contentTag = sub_soup.find_all('div', {'class': '_1665V undefined'})

    date = None
    title = None
    content = None

    if isinstance(dateTag, Tag):
        date = dateTag.get_text().strip()

    if isinstance(titleTag, Tag):
        title = titleTag.get_text().strip()

    if isinstance(contentTag, list):
        content = []
        for c in contentTag:
            content.append(c.get_text().strip())
        content = ' '.join(content)

    print(f'{date}\n {title}\n {content}\n')

    time.sleep(3)  


browser.close()

为什么在几篇文章之后,这段代码为什么不再提供内容呢?我不明白

谢谢。

1 个答案:

答案 0 :(得分:2)

这是因为1 15 9 18.5 9 18.5 9 18.5 17 12 这是显示几页后显示在网页上的消息。