Maison développement back-end Tutoriel Python Utilisez Python pour explorer les articles du site Web en prose

Utilisez Python pour explorer les articles du site Web en prose

Jul 03, 2017 pm 05:30 PM
python article


image.png

Configurer python 2.7

<code>    bs4

    requests</code>
Copier après la connexion

Installation avec pip sudo pip install bs4

Demandes d'installation sudo pip

Expliquez brièvement l'utilisation de bs4 car il explore des pages Web, je vais donc vous présenter find et find_all

La différence entre find et find_all est que ce qui est renvoyé est différent. Ce qui renvoie est la première balise correspondante et le contenu de la balise

find_all renvoie une liste

Par exemple, nous écrivons un test.html pour tester la différence entre find et find_all. Le contenu est :

<html>
<head>
</head>
<body>
<div id="one"><a></a></div>
<div id="two"><a href="#">abc</a></div>
<div id="three"><a href="#">three a</a><a href="#">three a</a><a href="#">three a</a></div>
<div id="four"><a href="#">four<p>four p</p><p>four p</p><p>four p</p> a</a></div>
</body>
</html>
Copier après la connexion

<code class="xml"><span class="hljs-tag"> </span></code>
Copier après la connexion

Alors le code de test.py est :

from bs4 import BeautifulSoup
import lxml

if __name__=='__main__':
  s = BeautifulSoup(open('test.html'),'lxml')
  print s.prettify()
  print "------------------------------"
  print s.find('div')
  print s.find_all('div')
  print "------------------------------"
  print s.find('div',id='one')
  print s.find_all('div',id='one')
  print "------------------------------"
  print s.find('div',id="two")
  print s.find_all('div',id="two")
  print "------------------------------"
  print s.find('div',id="three")
  print s.find_all('div',id="three")
  print "------------------------------"
  print s.find('div',id="four")
  print s.find_all('div',id="four")
  print "------------------------------"
Copier après la connexion

<code class="python"><span class="hljs-keyword"> </span></code>
Copier après la connexion

Après l'exécution, nous pouvons voir le résultat. Lors de l'obtention de la balise spécifiée, il n'y a pas beaucoup de différence entre les deux. Lors de l'obtention d'un groupe de balises, la différence entre les deux sera affichée

.

image.png

Nous devons donc faire attention à ce dont nous avons besoin lorsque nous l'utilisons, sinon une erreur se produira
L'étape suivante consiste à obtenir des informations sur la page Web via des requêtes. Je ne comprends pas très bien pourquoi d'autres écrivent et d'autres choses.
Moi Accédez directement à la page Web, obtenez les pages Web de deuxième niveau de plusieurs catégories sur prose.com via la méthode get, puis réussissez un test de groupe pour explorer toutes les pages Web

<span style="color: #0000ff">def</span><span style="color: #000000"> get_html():
  url </span>= <span style="color: #800000">"</span><span style="color: #800000"></span><span style="color: #800000">"</span><span style="color: #000000">
  two_html </span>= [<span style="color: #800000">'</span><span style="color: #800000">sanwen</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">shige</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">zawen</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">suibi</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">rizhi</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">novel</span><span style="color: #800000">'</span><span style="color: #000000">]
  </span><span style="color: #0000ff">for</span> doc <span style="color: #0000ff">in</span><span style="color: #000000"> two_html:
      i</span>=1
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">sanwen</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">"</span><span style="color: #800000">running sanwen -----------------------------</span><span style="color: #800000">"</span>
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">shige</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">"</span><span style="color: #800000">running shige ------------------------------</span><span style="color: #800000">"</span>
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">zawen</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running zawen -------------------------------</span><span style="color: #800000">'</span>
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">suibi</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running suibi -------------------------------</span><span style="color: #800000">'</span>
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">rizhi</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running ruzhi -------------------------------</span><span style="color: #800000">'</span>
          <span style="color: #0000ff">if</span> doc==<span style="color: #800000">'</span><span style="color: #800000">nove</span><span style="color: #800000">'</span><span style="color: #000000">:
            </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running xiaoxiaoshuo -------------------------</span><span style="color: #800000">'</span>
      <span style="color: #0000ff">while</span>(i<10<span style="color: #000000">):
        par </span>= {<span style="color: #800000">'</span><span style="color: #800000">p</span><span style="color: #800000">'</span><span style="color: #000000">:i}
        res </span>= requests.get(url+doc+<span style="color: #800000">'</span><span style="color: #800000">/</span><span style="color: #800000">'</span>,params=<span style="color: #000000">par)
        </span><span style="color: #0000ff">if</span> res.status_code==200<span style="color: #000000">:
          soup(res.text)
              i</span>+=i
Copier après la connexion

<code class="python"><span class="hljs-function"><span class="hljs-keyword"> </span></span></code>
Copier après la connexion
Copier après la connexion
Copier après la connexion

Dans cette partie du code, je n'ai pas traité le res.status_code qui n'est pas 200. Le problème qui en résulte est que les erreurs ne seront pas affichées et le contenu exploré sera perdu. Ensuite, j'ai analysé la page Web de Sanwen.net et j'ai découvert qu'il s'agissait de www.sanwen.net/rizhi/&p=1
La valeur maximale de p est 10. Je ne comprends pas la dernière fois que j'ai exploré le disque, c'était 100 pages, je l'analyserai plus tard. Récupérez ensuite le contenu de chaque page via la méthode get.
Après avoir obtenu le contenu de chaque page, l'auteur et le titre sont analysés. Le code est le suivant

<span style="color: #0000ff">def</span><span style="color: #000000"> soup(html_text):
  s </span>= BeautifulSoup(html_text,<span style="color: #800000">'</span><span style="color: #800000">lxml</span><span style="color: #800000">'</span><span style="color: #000000">)
  link </span>= s.find(<span style="color: #800000">'</span><span style="color: #800000">div</span><span style="color: #800000">'</span>,class_=<span style="color: #800000">'</span><span style="color: #800000">categorylist</span><span style="color: #800000">'</span>).find_all(<span style="color: #800000">'</span><span style="color: #800000">li</span><span style="color: #800000">'</span><span style="color: #000000">)
  </span><span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span><span style="color: #000000"> link:
    </span><span style="color: #0000ff">if</span> i!=s.find(<span style="color: #800000">'</span><span style="color: #800000">li</span><span style="color: #800000">'</span>,class_=<span style="color: #800000">'</span><span style="color: #800000">page</span><span style="color: #800000">'</span><span style="color: #000000">):
      title </span>= i.find_all(<span style="color: #800000">'</span><span style="color: #800000">a</span><span style="color: #800000">'</span>)[1<span style="color: #000000">]
      author </span>= i.find_all(<span style="color: #800000">'</span><span style="color: #800000">a</span><span style="color: #800000">'</span>)[2<span style="color: #000000">].text
      url </span>= title.attrs[<span style="color: #800000">'</span><span style="color: #800000">href</span><span style="color: #800000">'</span><span style="color: #000000">]
      sign </span>= re.compile(r<span style="color: #800000">'</span><span style="color: #800000">(//)|/</span><span style="color: #800000">'</span><span style="color: #000000">)
      match </span>=<span style="color: #000000"> sign.search(title.text)
      file_name </span>=<span style="color: #000000"> title.text
      </span><span style="color: #0000ff">if</span><span style="color: #000000"> match:
        file_name </span>= sign.sub(<span style="color: #800000">'</span><span style="color: #800000">a</span><span style="color: #800000">'</span>,str(title.text))
Copier après la connexion

<code class="python"><span class="hljs-function"><span class="hljs-keyword"> </span></span></code>
Copier après la connexion
Copier après la connexion
Copier après la connexion

Quelque chose n'allait pas lors de l'obtention du titre. Les gars, pourquoi ajoutez-vous des barres obliques dans le titre lors de l'écriture de la prose ? Ce problème a directement fait apparaître le nom du fichier lorsque j'ai écrit le fichier plus tard. alors écrivez une expression régulière et je la changerai pour vous.
La dernière étape consiste à obtenir le contenu en prose. Grâce à l'analyse de chaque page, l'adresse de l'article est obtenue, puis le contenu est obtenu directement. A l'origine, je voulais l'obtenir un par un directement en changeant de page web. adresse, ce qui évite des ennuis.

<span style="color: #0000ff">def</span><span style="color: #000000"> get_content(url):
  res </span>= requests.get(<span style="color: #800000">'</span><span style="color: #800000"></span><span style="color: #800000">'</span>+<span style="color: #000000">url)
  </span><span style="color: #0000ff">if</span> res.status_code==200<span style="color: #000000">:
    soup </span>= BeautifulSoup(res.text,<span style="color: #800000">'</span><span style="color: #800000">lxml</span><span style="color: #800000">'</span><span style="color: #000000">)
    contents </span>= soup.find(<span style="color: #800000">'</span><span style="color: #800000">div</span><span style="color: #800000">'</span>,class_=<span style="color: #800000">'</span><span style="color: #800000">content</span><span style="color: #800000">'</span>).find_all(<span style="color: #800000">'</span><span style="color: #800000">p</span><span style="color: #800000">'</span><span style="color: #000000">)
    content </span>= <span style="color: #800000">''</span>
    <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span><span style="color: #000000"> contents:
      content</span>+=i.text+<span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span>
    <span style="color: #0000ff">return</span> content
Copier après la connexion

<code class="python"><span class="hljs-function"><span class="hljs-keyword"> </span></span></code>
Copier après la connexion
Copier après la connexion
Copier après la connexion

La dernière chose est d'écrire le fichier et de le sauvegarder ok

   f = open(file_name+<span style="color: #800000">'</span><span style="color: #800000">.txt</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">w</span><span style="color: #800000">'</span><span style="color: #000000">)

      </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running w txt</span><span style="color: #800000">'</span>+file_name+<span style="color: #800000">'</span><span style="color: #800000">.txt</span><span style="color: #800000">'</span><span style="color: #000000">
      f.write(title.text</span>+<span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span><span style="color: #000000">)
      f.write(author</span>+<span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span><span style="color: #000000">)
      content</span>=<span style="color: #000000">get_content(url)     
      f.write(content)
      f.close()</span>
Copier après la connexion

Les trois fonctions obtiennent la prose de Prose.com, mais il y a un problème. Le problème est que je ne sais pas pourquoi de la prose est perdue. Je ne peux obtenir qu'environ 400 articles, ce qui est très différent des articles. de Prose.com, mais c'est vrai. Il a été obtenu page par page. J'espère que quelqu'un pourra m'aider avec cette question. Peut-être devrions-nous rendre la page Web inaccessible. Bien sûr, je pense que cela a quelque chose à voir avec le réseau cassé dans mon dortoir

.
     f = open(file_name+<span style="color: #800000">'</span><span style="color: #800000">.txt</span><span style="color: #800000">'</span>,<span style="color: #800000">'</span><span style="color: #800000">w</span><span style="color: #800000">'</span><span style="color: #000000">)
      </span><span style="color: #0000ff">print</span> <span style="color: #800000">'</span><span style="color: #800000">running w txt</span><span style="color: #800000">'</span>+file_name+<span style="color: #800000">'</span><span style="color: #800000">.txt</span><span style="color: #800000">'</span><span style="color: #000000">
      f.write(title.text</span>+<span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span><span style="color: #000000">)
      f.write(author</span>+<span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span><span style="color: #000000">)
      content</span>=<span style="color: #000000">get_content(url)     
      f.write(content)
      f.close()</span>
Copier après la connexion

J'ai failli oublier les rendus

Bien que le code soit compliqué, je ne m'arrête jamais

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

PHP et Python: différents paradigmes expliqués PHP et Python: différents paradigmes expliqués Apr 18, 2025 am 12:26 AM

PHP est principalement la programmation procédurale, mais prend également en charge la programmation orientée objet (POO); Python prend en charge une variété de paradigmes, y compris la POO, la programmation fonctionnelle et procédurale. PHP convient au développement Web, et Python convient à une variété d'applications telles que l'analyse des données et l'apprentissage automatique.

Choisir entre PHP et Python: un guide Choisir entre PHP et Python: un guide Apr 18, 2025 am 12:24 AM

PHP convient au développement Web et au prototypage rapide, et Python convient à la science des données et à l'apprentissage automatique. 1.Php est utilisé pour le développement Web dynamique, avec une syntaxe simple et adapté pour un développement rapide. 2. Python a une syntaxe concise, convient à plusieurs champs et a un écosystème de bibliothèque solide.

Python vs JavaScript: la courbe d'apprentissage et la facilité d'utilisation Python vs JavaScript: la courbe d'apprentissage et la facilité d'utilisation Apr 16, 2025 am 12:12 AM

Python convient plus aux débutants, avec une courbe d'apprentissage en douceur et une syntaxe concise; JavaScript convient au développement frontal, avec une courbe d'apprentissage abrupte et une syntaxe flexible. 1. La syntaxe Python est intuitive et adaptée à la science des données et au développement back-end. 2. JavaScript est flexible et largement utilisé dans la programmation frontale et côté serveur.

Peut-on exécuter le code sous Windows 8 Peut-on exécuter le code sous Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code peut fonctionner sur Windows 8, mais l'expérience peut ne pas être excellente. Assurez-vous d'abord que le système a été mis à jour sur le dernier correctif, puis téléchargez le package d'installation VS Code qui correspond à l'architecture du système et l'installez comme invité. Après l'installation, sachez que certaines extensions peuvent être incompatibles avec Windows 8 et doivent rechercher des extensions alternatives ou utiliser de nouveaux systèmes Windows dans une machine virtuelle. Installez les extensions nécessaires pour vérifier si elles fonctionnent correctement. Bien que le code VS soit possible sur Windows 8, il est recommandé de passer à un système Windows plus récent pour une meilleure expérience de développement et une meilleure sécurité.

L'extension VScode est-elle malveillante? L'extension VScode est-elle malveillante? Apr 15, 2025 pm 07:57 PM

Les extensions de code vs posent des risques malveillants, tels que la cachette de code malveillant, l'exploitation des vulnérabilités et la masturbation comme des extensions légitimes. Les méthodes pour identifier les extensions malveillantes comprennent: la vérification des éditeurs, la lecture des commentaires, la vérification du code et l'installation avec prudence. Les mesures de sécurité comprennent également: la sensibilisation à la sécurité, les bonnes habitudes, les mises à jour régulières et les logiciels antivirus.

Le code Visual Studio peut-il être utilisé dans Python Le code Visual Studio peut-il être utilisé dans Python Apr 15, 2025 pm 08:18 PM

VS Code peut être utilisé pour écrire Python et fournit de nombreuses fonctionnalités qui en font un outil idéal pour développer des applications Python. Il permet aux utilisateurs de: installer des extensions Python pour obtenir des fonctions telles que la réalisation du code, la mise en évidence de la syntaxe et le débogage. Utilisez le débogueur pour suivre le code étape par étape, trouver et corriger les erreurs. Intégrez Git pour le contrôle de version. Utilisez des outils de mise en forme de code pour maintenir la cohérence du code. Utilisez l'outil de liaison pour repérer les problèmes potentiels à l'avance.

PHP et Python: une plongée profonde dans leur histoire PHP et Python: une plongée profonde dans leur histoire Apr 18, 2025 am 12:25 AM

PHP est originaire en 1994 et a été développé par Rasmuslerdorf. Il a été utilisé à l'origine pour suivre les visiteurs du site Web et a progressivement évolué en un langage de script côté serveur et a été largement utilisé dans le développement Web. Python a été développé par Guidovan Rossum à la fin des années 1980 et a été publié pour la première fois en 1991. Il met l'accent sur la lisibilité et la simplicité du code, et convient à l'informatique scientifique, à l'analyse des données et à d'autres domaines.

Comment exécuter des programmes dans Terminal Vscode Comment exécuter des programmes dans Terminal Vscode Apr 15, 2025 pm 06:42 PM

Dans VS Code, vous pouvez exécuter le programme dans le terminal via les étapes suivantes: Préparez le code et ouvrez le terminal intégré pour vous assurer que le répertoire de code est cohérent avec le répertoire de travail du terminal. Sélectionnez la commande Run en fonction du langage de programmation (tel que Python de Python your_file_name.py) pour vérifier s'il s'exécute avec succès et résoudre les erreurs. Utilisez le débogueur pour améliorer l'efficacité du débogage.

See all articles