【发布时间】:2019-02-20 21:28:07
【问题描述】:
我的总体目标是拥有一个在网站 url 期间不会被抓取的 url 的数组/列表,如下面的代码示例中所示的逻辑是
('scrapy.py') 的逻辑:
在 ('source') 中打开 url ~> 从 ('source') 中的 url 中找到 'a' 标签 ~> 在 'a' 标签中找到 'href' ~> 如果 'href' 的值不等于( !=) ('done') 在文件 ('doneurls.py') ~> 然后将不等于 ('done') 的 url 写入文件 ('url.py')
我使用的代码是'scrapy.py':
from bs4 import BeautifulSoup
import requests
import csv
import os
import sys
from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))
from doneurls import done
source = requests.get('http://localhost/index.php').text
soup = BeautifulSoup(source, 'lxml')
file = open('./url.py', 'a')
csv_writer = csv.writer(file)
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self,tag,attrs):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, print it.
if name == "href":
if value != done:
csv_writer.writerow('b="'+value+'"')
parser = MyHTMLParser()
parser.feed(source)
file.close()
index.php:
<a href="http://localhost/next.php">hello</a>
<a href="http://localhost/next3.php">hello</a>
<a href="http://localhost/next2.php">hello</a>
<a href="http://localhost/next1.php">hello</a>
<a href="http://localhost/1.php">hello</a>
<a href="http://localhost/2.php">hello</a>
<a href="http://localhost/3.php">hello</a>
doneurls.py:
done = "http://localhost/2.php"
这段代码似乎有效,它只忽略了我添加到 doneurls.py 的一个 url 并且运行良好,但我想要做的是添加一组 url 来完成这样的操作
done = {
"http://localhost/2.php",
"http://localhost/next1.php",
"http://localhost/next2.php"}
当我尝试将“完成”作为数组运行时,根本不会跳过任何网址。我正在使用此代码来尝试不必抓取我过去抓取的网址。
【问题讨论】:
-
请描述您的问题,而不是代码并格式化您的代码。
-
问题正在修改中。也许新信息会提供更多的说明。
标签: python beautifulsoup xampp python-requests export-to-csv