【问题标题】:Python Web Scraping - Is it not possible to scrape this site?Python Web Scraping - 不能抓取这个网站吗?
【发布时间】:2021-06-27 21:15:42
【问题描述】:

我要抓取以下网站:https://www.globenewswire.com/NewsRoom

我的目标是将新闻稿和文章存储在我以后使用的数据库中。我在其他新闻网站上也这样做过,并删除了此处的代码以便于阅读(100% 对提供给您的代码没有影响)。我的问题是我无法弄清楚如何准确地抓取标题、链接和其他数据,因为 html 代码的结构具有不寻常的属性。

以下代码是我处理它的方式。也许有人知道我在抓取时犯了什么错误。非常感谢任何帮助。

import requests
import sqlite3
import Keywords
from bs4 import BeautifulSoup
from time import sleep
from random import randint
from datetime import datetime
from datetime import timedelta


# ----- Initializing Database & Notification Service -----
connect = sqlite3.connect('StoredArticles.db')
cursor = connect.cursor()
print("Connection created.")


try:
    cursor.execute('''CREATE TABLE articlestable (article_time TEXT, article_title TEXT, article_keyword TEXT, 
    article_link TEXT, article_description TEXT, article_entry_time DATETIME)''')
    cursor.execute('''CREATE UNIQUE INDEX index_article_link ON articlestable(article_link)''')
except:
    pass
print("Table ready.")

while True:

    class Scrapers:

        # ----- Initialize Keywords -----
        def __init__(self):
            self.article_keyword = None
            self.article_title = None
            self.article_link = None
            self.article_time = None
            self.article_time_drop = None
            self.article_description = None
            self.article_entry_time = None
            self.headers = {
                'User-Agent':
                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko)' +
                    'Version/14.0.1 Safari/605.1.15'
            }

        def scraping_globenewswire(self, page):
            url = 'https://www.globenewswire.com/NewsRoom?page=' + str(page)
            r = requests.get(url, headers=self.headers)
            soup = BeautifulSoup(r.text, 'html.parser')

            articles = soup.select('.main-container > .row')
            print("GlobeNewswire - Scraping page " + str(page) + "...")
            sleep(randint(0, 1))

            for item in articles:
                self.article_title = item.select_one('a[data-autid="article-url"]').text.strip()
                self.article_time = item.select_one('span[data-autid="article-published-date"]').text.strip()
                self.article_link = 'https://www.globenewswire.com' + \
                                    item.select_one('a[data-autid="article-url"]')['href']
                self.article_description = item.select_one('span', _class='pagging-list-item-text-body').text.strip()
                self.article_entry_time = datetime.now()
                cursor.execute('''INSERT OR IGNORE INTO articlestable VALUES(?,?,?,?,?,?)''',
                               (self.article_time, self.article_title, self.article_keyword, self.article_link,
                                self.article_description, self.article_entry_time))
                print(self.article_title)
            return


    # ----- End of Loops -----

    scraper = Scrapers()

    # ----- Range of Pages to scrape through -----
    for x in range(1, 3):
        scraper.scraping_globenewswire(x)


    # ----- Add to Database -----
    connect.commit()
    print("Process done. Starting to sleep again. Time: " + str(datetime.now()))
    sleep(randint(5, 12))

【问题讨论】:

标签: python web-scraping


【解决方案1】:

我从给定的 URL 中提取了 page=1 的所有标题。

标题出现在<a> 中,属性data-autid 等于article-url

  • 使用findAll()选择所有具有上述属性的<a>
  • 遍历上面所有选定的<a> 并提取标题,即文本
  • 您可以扩展它并使用这种方法提取您需要的任何数据。

此代码将从给定 URL 打印 page=1 的所有标题。

import requests
import bs4 as bs

url = 'https://www.globenewswire.com/NewsRoom'
resp = requests.get(url)
soup = bs.BeautifulSoup(resp.text, 'lxml')

headlines = soup.findAll('a', attrs={'data-autid': 'article-url'})

for i in headlines:
    print(i.text, end="\n")

【讨论】:

  • 非常感谢!这帮助我解决了我的问题:)
猜你喜欢
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2021-06-07
相关资源
最近更新 更多